PythonでMySQL基本操作

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

ここからmysql-connector-pythonのzipファイルをダウンロード.

Index of Packages : Python Package Index

そして、解凍先へ行って

python setup.py install

するだけ。

コード

import mysql.connector

try:
    cnn = mysql.connector.connect(host='localhost',
                                  db='データベース名',
                                  user='ユーザ名',
                                  passwd='パスワード',
                                  port=ポート番号,
                                  charset='文字コード'
                                  )

    # 例で t1 というテーブル作ってます
    cur = cnn.cursor(buffered=True)
    cur.execute("drop table if exists t1")
    cur.execute("create table t1 (a int,b int)")

    sql = "insert into t1 values "

    for j in range(100):
        for i in range(10000):
            sql += "("+str(i)+","+str(i)+"),"
        sql += "("+str(-1)+","+str(-1)+")"
        cur.execute(sql)
        cnn.commit()
        sql = "insert into t1 values "

except Exception as e:
    print e

参考文献

[Python][SQL]mysql.connectorが使えるようになるまで | Momentum