格式指定符不会被选择查询中的值替换从python传递到mysql

我试图从python查询sql数据库。 当我直接在字符串中筛选过滤器的值并将i作为查询传递时,查询是合适的。然而,当我使用格式说明符像“%s”我正面临问题。格式指定符不会被选择查询中的值替换从python传递到mysql

代码是如在此,如果我给%d为格式说明和= 2偶然后我面对错误如下

[import tkinter 

import tkinter.messagebox

from tkinter import *

import mysql.connector

top = tkinter.Tk()

#database connecion

from mysql.connector import errorcode

try:

cnx =mysql.connector.connect(host='localhost',user='root',password='1234')

cur = cnx.cursor()

query="CREATE DATABASE IF NOT EXISTS prj_db"

cur.execute(query)

cnx =mysql.connector.connect(host='localhost',database='prj_db',user='root',password='1234')

except mysql.connector.Error as err:

if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:

print("Something is wrong with your user name or password")

elif err.errno == errorcode.ER_BAD_DB_ERROR:

print("no db")

else:

print(err)

else:

cur = cnx.cursor()

query = ("CREATE TABLE IF NOT EXISTS product_det_2"

"(P_id INT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,"

"P_name CHAR(20) DEFAULT '' NOT NULL,"

"Drawing_num CHAR(20) DEFAULT '' NOT NULL,"

"Price INT(4) UNSIGNED ZEROFILL NOT NULL,"

"PRIMARY KEY(P_id))")

cur.execute(query)

query = ("SELECT * FROM product_det_2")

cur.execute(query)

print(query)

for (P_id, P_name, Drawing_num,Price) in cur:

print("{}, {}, {},{}".format(P_id, P_name, Drawing_num,Price))

print("*********************************")

query = ("SELECT * FROM product_det_2 WHERE P_id=2")

print(query)

cur.execute(query)

for (P_id, P_name, Drawing_num,Price) in cur:

print("{}, {}, {},{}".format(P_id, P_name, Drawing_num,Price))

print("*********************************")

a="2"

query = ("SELECT * FROM product_det_2 WHERE P_id=%s")

print(query)

cur.execute(query,a)

for (P_id, P_name, Drawing_num,Price) in cur:

print("{}, {}, {},{}".format(P_id, P_name, Drawing_num,Price))

cnx.commit()

top.mainloop()][1]

。 请让我知道我错了enter image description here

回答:

的第二个参数cursor.execute()应该是一个元组或字典。即使只有一个参数插入到查询中,也是如此。试试这个:

cur.execute(query, (a,)) 

这里一个包含单个元素的元组被传递给​​。

以上是 格式指定符不会被选择查询中的值替换从python传递到mysql 的全部内容, 来源链接: utcz.com/qa/260919.html

回到顶部