DBに特定のデータがあるかどうかを確認する
DB内にデータがあるかどうか確認する。
あった時は更新(update)、なかった時は挿入(insert)するように処理すればよい。
cur.execute(sql,data)に渡した時にSQL文がうまく展開されない?問題で困った。
# -*- coding: utf-8 import mysql.connector import datetime config = { 'user': 'root', 'password': 'password', 'host': 'localhost', 'database':'testdb', 'charset':'utf8' } cnx = mysql.connector.connect(**config) cur = cnx.cursor(buffered=True) #tableの削除と作成 sql = 'DROP TABLE IF EXISTS TEST_UPDATE;' cur.execute(sql) cnx.commit() sql = 'CREATE TABLE IF NOT EXISTS TEST_UPDATE (\ id INT UNSIGNED NOT NULL AUTO_INCREMENT,\ time DATETIME DEFAULT NULL, \ value1 INT UNSIGNED DEFAULT NULL ,\ value2 INT UNSIGNED DEFAULT NULL ,\ primary key(id),\ unique (time));' cur.execute(sql) cnx.commit() #初期データのインサート sql = 'INSERT INTO TEST_UPDATE (time, value1,value2) VALUES (%s, %s, %s);' data= ('2017-5-01T05:50:00','1','1') cur.execute(sql, data) sql = 'INSERT INTO TEST_UPDATE (time, value1,value2) VALUES (%s, %s, %s);' data= ('2017-5-01T05:50:05','2','2') cur.execute(sql, data) cnx.commit() #この時点でのテーブルの中身 #mysql> select * from test_update; #+----+---------------------+--------+--------+ #’ id | time | value1 | value2 | #+----+---------------------+--------+--------+ #| 1 | 2017-05-01 05:50:00 | 1 | 1 | #| 2 | 2017-05-01 05:50:05 | 2 | 2 | #+----+---------------------+--------+--------+ #2 rows in set (0.00 sec) #データの有無の確認1 sql= "select exists(select * from test_update where time=%s);" #data=(datetime.datetime(2017,5,1,5,50,00),) data= ('2017-5-01T05:50:00',)#なぜかカンマが必要。 try: cur.execute(sql,data) except mysql.connector.Error as err: print(cur.statement)#実行したSQL文の確認 raise #print(cur.fetchone()) #あった時…(1,) #なかった時…(0,) if cur.fetchone()[0]==0: print("なかった") else: print("あった") #データの有無の確認2 #テーブル名をdataで渡そうとすると、クォートがついてしまってうまく動かない。 tablename='test_update' sql= "select exists(select * from " + tablename +" where time=%s);" data= ('2017-5-01T05:50:05',) try: cur.execute(sql,data) except mysql.connector.Error as err: print(cur.statement)#実行したSQL文の確認 raise if cur.fetchone()[0]==0: print("なかった") else: print("あった") #データの有無の確認3 tablename='test_update' sql= "select exists(select * from " + tablename +" where time=%s);" data= ('2017-5-01T05:50:15',) try: cur.execute(sql,data) except mysql.connector.Error as err: print(cur.statement)#実行したSQL文の確認 raise if cur.fetchone()[0]==0: print("なかった") else: print("あった") cur.close() cnx.close() print('end')