Help us understand the problem. What is going on with this article?

PythonからMySQLを使う

More than 5 years have passed since last update.

そろそろオワコン感が出てきそうな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がカラム名と値の辞書になります。

pfn
Make the real world computable / 現実世界を計算可能にする
https://preferred.jp/ja/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした