我正在尝试使用flask + sqlalchemy在MSSQL中向我的表中插入一些数据。我正在使用Python 3.4。 我的代码:
@main.route('/create-user', methods=['GET', 'POST'])
def create_user():
form = NewUser()
if form.validate_on_submit():
login = form.name.data
passwrd = form.password.data
print (login) #getting login is ok
print (passwrd) #same
engine.execute(
text("INSERT INTO my_table VALUES ((CONVERT(binary, :login)), (CONVERT(binary, :passwrd)))"), login, passwrd)
session.commit()
flash('Succesfull')
return redirect(url_for('main.index'))
return render_template('new_user.html', form=form)
但我得到一个错误:
AttributeError: 'tuple' object has no attribute 'keys'
回溯:
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python34\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python34\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python34\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python34\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\flask_prj\project\app\main\views.py", line 35, in create_user
text("INSERT INTO my_table VALUES ((CONVERT(binary, :login)), (CONVERT(binary, :passwrd)))"), login, passwrd)
File "C:\Python34\lib\site-packages\sqlalchemy\engine\base.py", line 1751, in execute
return connection.execute(statement, *multiparams, **params)
File "C:\Python34\lib\site-packages\sqlalchemy\engine\base.py", line 729, in execute
return meth(self, multiparams, params)
File "C:\Python34\lib\site-packages\sqlalchemy\sql\elements.py", line 322, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Python34\lib\site-packages\sqlalchemy\engine\base.py", line 802, in _execute_clauseelement
keys = distilled_params[0].keys()
AttributeError: 'tuple' object has no attribute 'keys'
我如何处理这个问题?
答案 0 :(得分:5)
如果在sql中使用命名占位符,则必须提供参数作为关键字参数。
所以,例如:
engine.execute(text("... ((CONVERT(binary, :login)), (CONVERT(binary, :passwrd)))"),
login=login, passwrd=passwrd)
或使用位置占位符:
engine.execute(text("... ((CONVERT(binary, %s)), (CONVERT(binary, %s)))"),
login, passwrd)
根据您实际使用的mssql连接器,在后一种情况下,您可能必须将%s
替换为?
。