我正在尝试使用MySQLdb查询我的数据库,但是当我发送带有参数的查询时,我得到click_button "submit", wait: 10
。我认为它与查询中的TypeError: not all arguments converted during string formatting
有关。如何解决此错误?
%s
:
Main.py
from flask import Flask, request
from app.config import DB
from app.items.items import ItemsAPI
app = Flask(__name__)
db = DB()
app.register_blueprint(ItemsAPI)
@app.route('/home')
def hello_world():
return "Welcome to Omnimoda."
@app.route('/dbtest', methods=['GET'])
def hello_database():
q_sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '%s'"
a_sql = "omnimoda"
test_request = db.query(q_sql, a_sql)
result_request = test_request.fetchall()
if (result_request is None):
return "Database does not exist."
else:
return "Database exists."
:
Items.py
from flask import Flask, request, jsonify, json, Blueprint
from app.config import DB
ItemsAPI = Blueprint('ItemsAPI', __name__)
db = DB()
@ItemsAPI.route('/items/listbycode', methods=['POST'])
def get_item_by_code():
value = request.form['value']
q_list_all = "SELECT * FROM item_info WHERE item_code = '%s'"
print q_list_all
a_list_all = (value)
items_request = db.query(q_list_all, a_list_all)
json_output = json.dumps(items_request.fetchall())
return json_output
:
config.py
回溯:
from flask import Flask
import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect(host="localhost", user="user", passwd="passwd", db="test_dbase")
self.conn.autocommit(True)
def query(self, sql, values):
try:
print values
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
答案 0 :(得分:6)
cursor.execute
期望列表作为其第二个参数
q_list_all = "SELECT * FROM item_info WHERE item_code = '%s'"
print q_list_all
a_list_all = (value,) #the comma makes it a list not the parens
items_request = db.query(q_list_all, a_list_all)
当你传递一个字符串
cur.execute(qry,"MyArg") # =becomes==> cur.execute(qry,["M","y","A","r","g"])
在某种程度上不相关的说明中,您应该考虑使用像sqlalchemy这样的ORM
答案 1 :(得分:5)
(value)
不是一个元组,它只是一个字符串。字符串是其字符的可迭代。所以实际上它好像你将输入字段中的字符列表传递给SQL语句,后者只有一个参数的空间。
改为使用(value,)
。