普段はPerl使いな私ですが、趣味でPythonを使った開発をするようになってから日々コードを書いて練習するようになりました。せっかくなので、自分の勉強メモをここに残しておきます。
何番煎じがわかりませんが、今回はmysql-connectorパッケージを使ったMySQLとの接続方法をメモします。
#開発環境
- CentOS:7.4
- MySQL:5.7.20
- Python 3.6.3 :: Anaconda, Inc.
#コマンド集
- mysql-connectorのインストール
# pip install mysql-connector-python-rf
- mysql-connectorでのMySQLとの接続
- cursor()は名前無しのカーソルであり、この状態でSQLを実行するとサーバー側のカーソルの宣言はなく、全行を取得する。
zisaku.py
import mysql.connector
conn = mysql.connector.connect(user='db_user',
password='db_password',
host='db_host',
database='db_name')
cur=conn.cursor()
- MySQLのテーブルを参照(select)
sql="select * from test_table"
cur.execute(sql)
- 参照した内容を標準出力
sql="select * from test_table"
cur.execute(sql)
row = cur.fetchone()
for i in row:
print(i)
- MySQLのテーブルに挿入(insert)
sql="insert into test_table (column1) values (test)"
cur.execute(sql)
conn.commit()
- カーソルの終了
cur.close()
- MySQLとの接続を切断
conn.close()
#参考文献
-
PythonとDB: DBIのcursorを理解する
https://qiita.com/knoguchi/items/3d5631505b3f08fa37cc -
MySQL公式ページ
https://dev.mysql.com/doc/