MySQL+Pythonのエラー
1 | ValueError: unsupported format character 'Y' (0x59) at index 51 |
このようなエラーが出るときの対応。
1 2 3 4 5 6 7 8 9 10 11 | import MySQLdb ymd="2017-05-19" con=MySQLdb.connect(user="root",password="",host="localhost",db="test") cur=con.cursor() cur.execute("set names utf8") # 文字化け対応 cur.execute("select * from test_table where date_format(ymd,'%%Y-%%m-%%d')=%s",(ymd,)) for row in cur.fetchall(): print(row[0]) |
これだと上記エラーが発生します。
ここに解決策が載っていました。
ポイントはsql文の文字列をformat()するだけ
1 2 3 4 5 6 7 8 9 10 11 | import MySQLdb ymd="2017-05-19" con=MySQLdb.connect(user="root",password="",host="localhost",db="test") cur=con.cursor() cur.execute("set names utf8") # 文字化け対応 cur.execute("select * from test_table where date_format(ymd,'%%Y-%%m-%%d')=%s".format(),(ymd,)) for row in cur.fetchall(): print(row[0]) |