python-如何使用原始输入编写正确的sql语句

azpvetkf  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(306)

基本上是用户输入plot id,我可以检查plot 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
cwtwac6a

cwtwac6a1#

而不是 (sql,(plot)) 格式,可以使用 format 直接如下。
代码:

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'

使用创建查询之后 format ,则可以执行

result = B_cur.execute(query)

相关问题