LoginSignup
5
3

More than 5 years have passed since last update.

メモ:Python3でMySQLを操作するには

Last updated at Posted at 2017-11-11

 普段は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()

参考文献

5
3
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
5
3