LoginSignup
80
82

More than 5 years have passed since last update.

PythonからMySQLを使う

Last updated at Posted at 2013-07-02

そろそろオワコン感が出てきそうなMySQLですが、
まだ普通に使うのでPythonからの使い方をメモっておきます。

ライブラリのインストール

MySQL-pythonを使います。
ちなみにこのライブラリはMariaDBにも対応しているらしいです。

pip install MySQL-python

debian系でエラーになる場合は
apt-get install python-dev
を実行すると解決する可能性があります

使い方

import MySQLdb
# DBへログイン
# localhostの場合は省略可
connection = MySQLdb.connect(db="test",user="test")

cursor = connection.cursor()
# SQL
cursor.execute("select * from users")
result = cursor.fetchall()

for row in result:
 p row[0]

cursor.close()
connection.close()

で、rowとしてSQL文の実行結果を1行づつ配列として取得できます。
また、MySQLdb.connectにcursorclass=MySQLdb.cursors.DictCursorを指定すると、
rowがカラム名と値の辞書になります。

80
82
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
80
82