我最近一直在用python编写与postgreSQL数据库一起工作的代码,它看起来像这样:
def insert(table, ID, date, timestamp):
cur.execute("""INSERT INTO %s (ID, date, timest)
VALUES (%s, %s, %s);""",
(AsIs(table), ID, AsIs(date), AsIs(timestamp)))
这似乎对postgreSQL工作得很好,但是当我在mySQL服务器上尝试同样的事情时,它不起作用。有人知道为什么吗?我认为这可能与%s字符有关,因为如果我硬编码表、ID、日期和时间戳的值,它就可以工作。
另外,它给了我以下错误:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''master'' at line 2")
'master'是我用作变量的表的名称,我还注意到master周围有两个单引号(像这样:' 'master' '),应该只有一个。所以这也可能是个问题?
不管怎样,谢谢你的帮助!
这在PostgreSQL中也不能正常工作。表名不应该被参数化。
cur.execute("""INSERT INTO table_name_here (ID, date, timest) ...
用于字符串连接:Postgres使用sql标准的双引号(不是两个单引号!):"master"
,这在默认的MySQL中不起作用。必须是`master`
-或仅仅是master
才能在两者中工作。
或者在MySQL中激活一些sql遵从性设置:
SET sql_mode = 'ANSI';
可以使用format函数:
sql = "INSERT INTO {0} (ID, date, timest) VALUES (%s, %s, %s);".format(table_name)
cursor.execute(sql, (ID, date, time_stamp))
实际上,我能够找出我问题的答案。简单地使用%代替,符号解决了我的问题。
原始代码:cur.execute("""INSERT INTO %s (ID, date, timest)
VALUES (%s, %s, %s);""",
(AsIs(table), ID, AsIs(date), AsIs(timestamp)))
固定代码:cur.execute("""INSERT INTO %s (ID, date, timest)
VALUES (%s, %s, %s);""" %
(AsIs(table), ID, AsIs(date), AsIs(timestamp)))