使用Python连接器插入字符串时出现Mysql语法错误

时间:2015-01-26 23:50:28

标签: python mysql

对MySQL和Python都很新,所以任何帮助都会受到赞赏。这种语法错误让我发疯,因为我觉得我完全按照教程...

这是我非常简单的数据库:

>>> cursor.execute('DESCRIBE Sports_Master')
>>> cursor.fetchall()
[(u'ID', u'int(11)', u'NO', u'PRI', None, u'auto_increment'), (u'Name', u'varchar(255)', u'NO', u'', None, u'')]

我试图做的事情:

import mysql.connector
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor()
test_name = 'Test'
insert_statement = ("INSERT INTO Sports_Master (Name) "
                    "VALUES (%s)"
                   )
cursor.execute(insert_statement, test_name)

这是由此产生的错误:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/mysql/connector/cursor.py", line 507, in execute
self._handle_result(self._connection.cmd_query(stmt))
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 722, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 640, in _handle_result
raise errors.get_exception(packet)
ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1

我有什么明显的错误吗?

1 个答案:

答案 0 :(得分:1)

IIRC,您传入的值应该是非字符串序列(如果您想使用%(name)语法,则为映射)。元组很适合你正在做的事情:

test_name = ('Test',)