我想使用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
答案 0 :(得分:0)
我假设您的<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Autofac" version="3.5.2" targetFramework="net451" />
<package id="Microsoft.Owin" version="3.1.0" targetFramework="net452" />
<package id="Microsoft.Owin.Host.HttpListener" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Hosting" version="3.1.0" targetFramework="net452" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net451" />
<package id="Owin" version="1.0" targetFramework="net451" />
<package id="Topshelf" version="3.2.0" targetFramework="net451" />
</packages>
列的数据类型为ModelName
。
把模型作为字符串。
varchar
您的查询应该像
model = "Intel(R) Xeon(R) CPU E5-2630 v2 @ 2.60GHz"
对于数据类型为Integer和Varchar的多个列。
mode= "INSERT INTO machinedetails (ModelName) VALUES (%s)"%(model)
cursor.execute(mode)
value1是Int,value2是String。 希望这能解决你的问题。 但我同意你不应该在生产代码中使用原始SQL的评论。