LoginSignup
3
1

More than 3 years have passed since last update.

PythonでMySQLにINSERTする【初心者向け】

Last updated at Posted at 2020-09-21

◎下記を参照してDBへのコネクト、SELECT分をためしてみる。
パッケージはmysqlclientを利用する
PythonでMySQLに接続する方法【初心者向け】

PythonでMySQLに接続する書き方は、そのままではエラーとなるので、下記を利用すること。

#mysqlclientパッケージを利用する
import MySQLdb

# 接続する
conn = MySQLdb.connect(
user='root',
passwd='root',
host='localhost',
db='mstibqym_crontest')

# カーソルを取得する
cur = conn.cursor()

# SQL(データベースを操作するコマンド)を実行する
sql = "select * from test_table"
cur.execute(sql)

# 実行結果を取得する
rows = cur.fetchall()

# 一行ずつ表示する
for row in rows:
    print(row)

cur.close

# 接続を閉じる
conn.close

◎INSERT分は下記を参考に実施
Python3でMySQLを使う – 基本操作からエラー処理までサンプルコード付

#mysqlclientパッケージを利用する
import MySQLdb

# 接続する
conn = MySQLdb.connect(
user='root',
passwd='root',
host='localhost',
db='mstibqym_crontest')

# カーソルを取得する
cur = conn.cursor()

# SQL(データベースを操作するコマンド)を実行する
sql = "INSERT INTO test_table (item) VALUES('xyzss')"
cur.execute(sql)

conn.commit()
cur.close

# 接続を閉じる
conn.close
3
1
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
3
1