gpt4 book ai didi

python - 我应该如何使用 raw_input 编写正确的 SQL 语句

转载 作者:行者123 更新时间:2023-11-29 18:02:50 24 4
gpt4 key购买 nike

基本上是用户输入绘图id,我可以检查数据库中是否存在绘图id。

请帮助我改进代码。谢谢

import MySQLdb
myConn = MySQLdb.connect("rds-mysql..........rds.amazonaws.com", "user", "", "db1")
print myConn
print("myConn Established!")
B_cur = myConn.cursor()
plot = raw_input("Enter plot ID: ")
sql = "SELECT * FROM mydb.Plot WHERE plot_id= %s"
result = B_cur.execute(sql,(plot))
print result.rowcount

错误消息是:

File "myConn.py", line 16, in <module>
result = B_cur.execute(sql,(plot))
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 210, in execute
query = query % args
TypeError: not all arguments converted during string formatting

最佳答案

您可以直接使用 format 来代替 (sql,(plot)) 格式,如下所示。

代码:

plot = raw_input("Enter plot ID: ")

sql = "SELECT * FROM mydb.Plot WHERE plot_id= %s"
query= sql,(plot)
print "Your query looks like --"
print query
print "--------------------------------------"
sql = "SELECT * FROM mydb.Plot WHERE plot_id = '{0}'"
query=sql.format(str(plot))
print "My query looks like --"
print query

输出:

Enter plot ID: 123
Your query looks like --
('SELECT * FROM mydb.Plot WHERE plot_id= %s', '123')
--------------------------------------
My query looks like --
SELECT * FROM mydb.Plot WHERE plot_id = '123'

一旦使用格式创建查询,就可以执行

result = B_cur.execute(query)

关于python - 我应该如何使用 raw_input 编写正确的 SQL 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48181831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com