Mysql连接器Python语法错误

时间:2015-12-11 18:04:08

标签: python mysql database connector

我想在tkinter界面中运行create函数,但它给了我这个错误:

  

1064(42000):您的SQL语法出错;检查手册   对应于您的MySQL服务器版本,以获得正确的语法   在'''附近使用(id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE,PRIMARY   第1行的KEY(id))'

这是代码。我尝试过很多想法但没有尝试......

    from mysql.connector import MySQLConnection, Error
    from tkinter import *

    DB_HOST = 'localhost'
    DB_USER = 'root'
    DB_PASS = 'mysql123'
    DB_NAME = 'Savings'

    def create(Name):
        try:
            connection = MySQLConnection(host=DB_HOST,user=DB_USER,password=DB_PASS,database=DB_NAME)
            cursor = connection.cursor()
            tabla = Name.get()
            cursor.execute("CREATE TABLE %s (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY KEY(id))", (tabla,))
            print("Hecho!")
        except Error as e:
            print(e)
        finally:
            connection.commit()
            cursor.close()
            connection.close()

1 个答案:

答案 0 :(得分:0)

无法参数化表格或列名称。使用字符串格式(但请确保您信任您的源或仔细验证输入表名称):

cursor.execute("CREATE TABLE {table} (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY KEY(id))".format(table=tabla))

请注意,您可以使用mysql连接器转义字符串:

tabla = connection.converter.escape(tabla)