Python:带格式插入数据库行

0 投票
3 回答
7038 浏览
提问于 2025-04-16 20:37

我正在尝试在我设置的数据库表中插入一行数据。

我的代码:

cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station) VALUES(%s, %s, %s, %s, timestamp, comport)""",[(prefix, code_id, answer, station)])

我遇到了一个错误,提示说“[]”里的内容有问题。

我对“%s”是怎么回事不是很明白。我试过很多例子,但都没有成功。

这个例子是我从 http://mysql-python.sourceforge.net/MySQLdb.html 上找到的。

3 个回答

-1

你可以使用Python的新方法来格式化字符串:

cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station) VALUES({}, {}, {}, {}, timestamp, comport)""".format(prefix, code_id, answer, station))

你也可以给参数编号,比如用"{0}"、"{1}",依此类推。根据你的Python版本,这可能是必须的(我记得2.6版本已经支持不带编号的参数)。

如果想了解更多关于如何使用这个方法的信息,可以查看这个链接:http://docs.python.org/library/string.html#format-examples

0
cursor.execute('INSERT INTO scan (prefix, code_id, answer, station) VALUES("%s", "%s", "%s", "%s")' %(prefix, code_id, answer, station))

如果你在使用 %s 时没有加上 "",比如直接用 %s 而不是 "%s",那么你可能会遇到错误。

2

为什么你在两个括号里放了参数呢?第二个参数应该是一个包含四个项目的序列,这样才能和你查询中的四个%s对应上。可是你给的却是一个只包含一个项目的列表:这个项目是一个包含四个项目的序列。

你可以试试这样:

cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station) VALUES(%s, %s, %s, %s, timestamp, comport)""",(prefix, code_id, answer, station))

撰写回答