LoginSignup
0
1

More than 1 year has passed since last update.

【備忘録】PythonでMySQLに接続しよう

Posted at

経緯

Pythonを使用してMySQLからデータを取得したい。
DBの列構成が変わっても結果に変化がないよう、辞書型を採用した。

ライブラリインストール

cmd
python -m pip install pymysql

ソース

python
import pymysql

SQL="SELECT * FROM userlist;"

mysql_kwargs = {
    "host":     "127.0.0.1",
    "port":     3306,
    "user":     "testuser",
    "password": "test",
    "database": "testdb",
}

conn = pymysql.connect(**mysql_kwargs)

# カーソルを取得する(辞書型)
cur = conn.cursor(pymysql.cursors.DictCursor)

# SQL実行
cur.execute(SQL)

# 実行結果を取得する
rows = cur.fetchall()

for row in rows:
    print(row["username"])

cur.close
conn.close

もし列名が不要の場合

下記を

python
cur = conn.cursor(pymysql.cursors.DictCursor)

このように変える。

python
cur = conn.cursor()

但し、列名では取得できなくなるので、値取得も下記のように変更する。

python
for row in rows:
    print(row[0]) #1列目の値を取得
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