【问题标题】:(Not all arguments converted during string formatting in python)(并非所有参数都在 python 中的字符串格式化期间转换)
【发布时间】:2017-12-01 11:12:06
【问题描述】:

我想使用 python 在 MySQL 查询中插入一个变量。我该怎么做?

我正在使用 python 2.7。

import MySQLdb

db = MySQLdb.connect("host","root","password","database" )

cursor = db.cursor()

model=Intel(R) Xeon(R) CPU E5-2630 v2 @ 2.60GHz

mode=("INSERT INTO machinedetails (ModelName) VALUES (%s)")

cursor.execute(mode,model)

data = cursor.fetchone()

print (data)

db.close()

-------------------------

Traceback (most recent call last):

File "System_Info.py", line 149, in <module>

 cursor.execute(mode,model)

 File "/usr/lib64/python2.7/site-packages/MySQLdb/cursors.py", line 187, in execute

query = query % tuple([db.literal(item) for item in args])\

TypeError: not all arguments converted during string formatting

【问题讨论】:

  • 您将mode 直接传递给execute 方法,而它需要一个可迭代的参数。试试cursor.execute(mode, [model])
  • 已发布多个同名问题。这就是为什么标题必须放在括号中的原因。类似的问题:stackoverflow.com/questions/18053500/…stackoverflow.com/questions/3089038/…
  • 您的型号无效... model = "Intel(R) Xeon(R) CPU E5-2630 v2 @ 2.60GHz"
  • 为什么还要在 Django 中使用原始 SQL?
  • 是的,发布了多个问题,但我的问题与其他问题不同@NoelWidmer

标签: python sql python-2.7


【解决方案1】:

我假设您的ModelName 列的数据类型是varchar。 以模型为字符串。

model = "Intel(R) Xeon(R) CPU E5-2630 v2 @ 2.60GHz"

你的查询应该是这样的

mode= "INSERT INTO machinedetails (ModelName) VALUES (%s)"%(model) cursor.execute(mode)

对于数据类型为 Integer 和 Varchar 的多个列。

Column1 Int Column2 Varchar query = "INSERT INTO machinedetails (Column1,Column2) VALUES (%s,%s)"%(value1, value2)

value1 是 Int,value2 是 String。 希望这能解决您的问题。 但我同意 cmets 你不应该在生产代码中使用原始 SQL。

【讨论】:

  • 我试过你的答案,错误已经消失,但我得到 ( ) 作为输出
  • 您是否在 SQL 服务器上检查过数据?如果您的数据库中有数据,还可以尝试使用fetchall()where 子句(假设您的数据库有多行)。
  • 等一下。我刚刚看到你在同一个光标对象上运行fetchone()fetchone()fetchall() 从游标中获取数据。从光标对象运行查询select top 1 * from machinedetails。然后在光标上执行fetchone()
  • @sachindubey 如果它适合您,请接受并投票回答。干杯!! :)
猜你喜欢
  • 2013-03-07
  • 2015-10-28
  • 2013-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
相关资源
最近更新 更多