MySQL db调用:并非所有参数在字符串格式化期间转换

时间:2018-02-04 13:16:10

标签: python mysql python-3.x

当我执行下面给出的代码时,我收到错误not all arguments converted during string formatting

pro_title = "FSBT"
print "pro_title: " + pro_title
pro_id_query = "SELECT ID FROM projs WHERE pro_title=%s"
cursor.execute(pro_id_query, pro_title)
db.commit()
row = cursor.fetchone()
pro_id = None
if row is not None:
   pro_id = str(row[0])    
print "pro_id: " + pro_id

我也试过format

pro_id_query = "SELECT ID FROM projs WHERE title={}"
cursor.execute(pro_id_query.format(pro_title))

仅当我在'周围使用{}时才有效:

pro_id_query = "SELECT ID FROM projs WHERE title='{}'"
cursor.execute(pro_id_query.format(pro_title))

我不明白为什么INSERT查询适用于%s,而SELECT查询却不能:

insert_query = "INSERT INTO projs (title, description) VALUES (%s, %s) ON DUPLICATE KEY UPDATE `title`=%s"
cursor.execute(insert_query, (pro_title, pro_description, pro_title))

1 个答案:

答案 0 :(得分:1)

pro_title = "FSBI" 
pro_id_query = "SELECT * FROM %s"%(pro_title)
cursor = con.cursor() 
cursor.execute(q) 
result_list = result.fetchall()   
result_list[0][0] 
con.commit() 
con.close()

pro_id_query = cursor.fetchone() while row != False:
print ("The ID is : ", row[0])

*修改

id = input("Id : ")
name = input("Name : ")
cursor = con.cursor()
cursor.execute(""" INSERT INTO names (id, name) VALUES("%s", "%s")"""
          %(id, name))