LoginSignup
0
0

More than 3 years have passed since last update.

pythonでのMysqlの使い方

Last updated at Posted at 2020-11-17

はじめに

この記事はYoloで受け取ったデータをもとに可視化する為の方法として,Mysqlを利用する方法を記入していくつもりです.
Mysqlの使い方は以下の記事を参考に記事にしていきたいと思います.

Python + mysql-connector-python の使い方まとめ
https://qiita.com/valzer0/items/2f27ba98397fa7ff0d74

環境

python8.x
xamppを利用(Mysql)

使用しているライブラリ

mysql.connector

データベースの構成

databasename:mask
table:mask-ok-or-ng1
カラム:3

name format
day day
time time
ok-or-ng text

実装したコード

def sqlng():
 day = datetime.date.today()
 time1 = datetime.datetime.now()
 conn = mydb.connect(
        host='127.0.0.1',
        port='3306',
        user='userid',#ユーザidの記入
        password='password',#パスワードの記入
        database='databasename'#データベースの名前を記入
    )
 # コネクションが切れた時に再接続してくれるよう設定
 conn.ping(reconnect=True)
 # 接続できているかどうか確認
 print(conn.is_connected())
 cur = conn.cursor()
 time2=str(time1.hour)+":"+str(time1.minute)+":"+str(time1.second)
 print(day)
 print(time2)
 cur.execute("INSERT INTO `mask-ok-or-ng1` (`day`, `time`, `ok-or-ng`)"+ "VALUES"+ "("+"'"+str(day)+"'"+","+"'"+str(time1)+"'"+","+"'NG')")
 conn.commit()
 cur.close()
 conn.close()

工夫している点としては,任意の変数をデータベースに挿入するときに,参照記事のやり方だとタプル型は使えないとエラーを吐かれたので上記のやり方でやりました.

# executemanyで複数データを一度に挿入
records = [
  (5, 'MONA', 3000),
  (6, 'XP', 1000),
]
cur.executemany("INSERT INTO test_table VALUES (%s, %s, %s)", records)

このやり方だとエラーを吐いた.
ここを下記のようにした.

 cur.execute("INSERT INTO `mask-ok-or-ng1` (`day`, `time`, `ok-or-ng`)"+ "VALUES"+ "("+"'"+str(day)+"'"+","+"'"+str(time1)+"'"+","+"'NG')")

最後に

これは個人的なメモ的に残しているので参考になると幸いです.

0
0
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
0
0