我正在尝试使用MySQLdb查询我的数据库,但是当我发送带有参数的查询时,我得到了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."
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
追溯:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/lanceguinto/Documents/Project_Omnimoda/API/app/items/items.py", line 26, in get_item_by_code
items_request = db.query(q_list_all, a_list_all)
File "/Users/lanceguinto/Documents/Project_Omnimoda/API/app/config.py", line 15, in query
cursor.execute(sql, values)
File "build/bdist.macosx-10.10-intel/egg/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
当你传递一个字符串
cur.execute(qry,"MyArg") # =becomes==> cur.execute(qry,["M","y","A","r","g"])
Run Code Online (Sandbox Code Playgroud)
你应该考虑使用像sqlalchemy这样的ORM
(value)不是一个元组,它只是一个字符串.字符串是其字符的可迭代.所以实际上就好像你将输入字段中的字符列表传递给SQL语句,后者只有一个参数的空间.
请(value,)改用.
| 归档时间: |
|
| 查看次数: |
7847 次 |
| 最近记录: |