在MySQL与PostgreSQL中执行语句时如何使用%s命令?
最近我在用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' '),其实应该只有一个。所以这可能也是个问题吧?
总之,谢谢大家的帮助!
3 个回答
0
你可以使用格式化函数:
sql = "INSERT INTO {0} (ID, date, timest) VALUES (%s, %s, %s);".format(table_name)
cursor.execute(sql, (ID, date, time_stamp))
2
在PostgreSQL中,这也不太好用。表名不应该被参数化。
cur.execute("""INSERT INTO table_name_here (ID, date, timest) ...
关于字符串连接:Postgres使用SQL标准的双引号(不是两个单引号!):"master"
,而在默认的MySQL中是不能用的。要在MySQL中使用,得用`master`
,或者直接用master
,这样在两者中都能工作。
或者可以在MySQL中激活一个设置,以便更符合SQL标准:
SET sql_mode = 'ANSI';
-3
其实,我找到了我问题的答案。只需用 % 代替 , 这个符号就解决了我的问题。
原始代码:
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)))