【发布时间】:2015-02-09 23:46:24
【问题描述】:
在 mysql 客户端中,以下查询可以完美运行:
INSERT INTO VOLUMES (VOLUMEID, NAME, TYPE, SERVERID,SIZE, DEVICENAME, CREATIONDATE) VALUES ('vol-b67d73b7', 'TBC','gp2', 'i-7d445a89', '8', '/dev/sda1', '2014-11-24T07:40:37.921Z');
但是,当我在我的 python 脚本中使用相同的查询时,我收到以下错误:
1265: Data truncated for column 'CREATIONDATE' at row 1
这是python代码:
try:
db = mysql.connector.connect(**config)
cursor = db.cursor()
for volume in volumes:
ins_stmt = ("INSERT INTO VOLUMES (VOLUMEID, NAME, TYPE, SERVERID,"
"SIZE, DEVICENAME, CREATIONDATE) VALUES ('{0}', 'TBC',"
"'{1}', '{2}', '{3}', '{4}', '{5}');")
to_execute = ins_stmt.format( volume.id, volume.type,
volume.attach_data.instance_id, volume.size,
volume.attach_data.device, volume.create_time)
cursor.execute(to_execute)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exists")
else:
print(err)
else:
db.close()
我不明白可能出了什么问题。有人可以帮忙吗?
【问题讨论】:
-
@MartijnPieters 已编辑,谢谢。
-
您不应该使用
str.format将值插入到查询中,这是一个巨大的SQL injection 风险。请查看the docs 了解如何完成的示例。