在python中将变量作为SQL值插入

时间:2013-04-22 15:33:46

标签: python sql pyodbc

exp = "Ted is a good film"
cursor.execute ("insert into films (descp) values (exp)")
cursor.commit()

我在MS SQL服务器上使用上面的代码,但它说:无效的列名'''' 我正在使用pyodbc。

3 个答案:

答案 0 :(得分:9)

cursor.execute ("insert into films (descp) values (?)",exp)

答案 1 :(得分:3)

我认为你应该将它作为一个元组传递:

cursor.execute ("insert into films (descp) values (?)", (exp,))

答案 2 :(得分:1)

您需要将exp内容作为字符串插入到insert表达式中。您可以使用string format和'':

exp = "Ted is a good film"
cursor.execute ("insert into films (descp) values ('{exp}')".format(exp=exp))
cursor.commit()