MySQLdb Python 插入 %d 和 %s

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20463333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:31:19  来源:igfitidea点击:

MySQLdb Python insert %d and %s

pythonmysqlmysql-python

提问by Matt Stokes

Precursor:

前体:

MySQL Table created via:
CREATE TABLE table(Id INT PRIMARY KEY NOT NULL, Param1 VARCHAR(50))

Function:

功能:

.execute("INSERT INTO table VALUES(%d,%s)", (int(id), string)

Output:

输出:

TypeError: %d format: a number is required, not a str

I'm not sure what's going on here or why I am not able to execute the command. This is using MySQLdb in Python. .executeis performed on a cursor object.

我不确定这里发生了什么或为什么我无法执行命令。这是在 Python 中使用 MySQLdb。.execute在游标对象上执行。

EDIT:

编辑:

The question: Python MySQLdb issues (TypeError: %d format: a number is required, not str)says that you must use %sfor all fields. Why might this be? Why does this command work?

问题:Python MySQLdb 问题 (TypeError: %d format: a number is required, not str)说您必须%s用于所有字段。为什么会这样?为什么这个命令有效?

.execute("INSERT INTO table VALUES(%s,%s)", (int(id), string)

采纳答案by noobmaster69

As the whole query needs to be in a string format while execution of query so %sshould be used...

由于在执行查询时整个查询需要采用字符串格式,因此%s应该使用...

After query is executed integer value is retained.

执行查询后保留整数值。

So your line should be.

所以你的线路应该是。

.execute("INSERT INTO table VALUES(%s,%s)", (int(id), string))

Explanation is here

解释在这里

回答by Arovit

You missed a '%'in string formatting

你错过了'%'字符串格式

"(INSERT INTO table VALUES(%d,%s)"%(int(id), string))

回答by lwzhuo

The format string is not really a normal Python format string. You must always use %s for all fields

格式字符串并不是一个普通的 Python 格式字符串。您必须始终对所有字段使用 %s

回答by wyz

I found a solution on dev.mysql.com. In short, use a dict, not a tuplein the second parameter of .execute():

我在dev.mysql.com上找到了一个解决方案。简而言之,在 的第二个参数中使用 a dict,而不是 a :tuple.execute()

add_salary = ("INSERT INTO salaries "
              "(emp_no, salary, from_date, to_date) "
              "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_salary = {
  'emp_no': emp_no,
  'salary': 50000,
  'from_date': tomorrow,
  'to_date': date(9999, 1, 1),
}

cursor.execute(add_salary, data_salary)