LoginSignup
0
1

More than 1 year has passed since last update.

Pyodbcを使用したデータベースへの接続方法

Posted at

PythonでSQLServerへ接続

業務の中でPythonを使用してSQLServerへ接続し、データを操作する簡単なスクリプトを作成する必要があったため、その備忘録として接続方法を残します。

1. Pyodbcのインストール

pip install pyodbc

2. データベースに接続

Pyodbcを使用してデータベースに接続するには、以下の手順を実行します。

インポート

Pyodbcモジュールをインポートします。

import pyodbc

接続文字列の作成

データベースに接続するために必要な接続文字列を作成します。接続文字列は、データベースの種類、サーバー名、データベース名、認証情報などの情報を含みます。

# 例(SQL Serverの場合)
connection_string = (
    r"DRIVER={ODBC Driver 17 for SQL Server};"
    r"SERVER=your_server_name;"
    r"DATABASE=your_database_name;"
    r"UID=your_username;"
    r"PWD=your_password;"
)

データベースへの接続

接続文字列を使用してデータベースに接続します。

connection = pyodbc.connect(connection_string)

3. データベース操作

データベースに接続した後、SQLクエリを実行してデータベースを操作できます。例として、データの取得や挿入を示します。

データの取得

cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table_name")

rows = cursor.fetchall()
for row in rows:
    print(row)

データの挿入

cursor = connection.cursor()
cursor.execute("INSERT INTO your_table_name ('column1', 'column2') VALUES ('value1', 'value2')")

変更を確定させる

connection.commit()

4. データベース接続の終了

データベース操作が完了したら、接続を閉じます。

connection.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