LoginSignup
0
1

More than 1 year has passed since last update.

【備忘】pyodbcでデータベースとテーブルを作成する

Last updated at Posted at 2021-06-02

プログラムの流れ

pyodbcでDB接続 → DB作成&テーブル作成 → DB切断

コード

import pyodbc

# インスタンス
instance = "<ipアドレス or サーバー名>"

# ユーザー
user = "<SQLServerのログインユーザー>"

# パスワード
pasword = "<パスワード>"

# DB接続
connection = (
    "DRIVER={SQL Server};SERVER=" + instance + ";uid=" + user + ";pwd=" + pasword
)
con = pyodbc.connect(connection, autocommit=True)
cursor = con.cursor()

# DB作成
cursor.execute("CREATE DATABASE mydb;")
# 作成したDBを指定してテーブル作成
cursor.execute(
        """
        USE mydb;
        CREATE TABLE mytable (
            column1 int,
            column2 nvarchar(50)
        );
        """
    )
# DB切断
cursor.close()

以上

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1