2015-12-11 104 views
0

我想運行在一個Tkinter的界面創建功能,但它給我這個錯誤:MySQL連接Python語法錯誤

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 ''' (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY KEY(id))' at line 1

這是代碼。我已經嘗試了很多想,但沒有...

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() 
+0

我是沒有Python的SQL人,但什麼是尾部逗號在最後一塊替換? '(tabla,)' – Drew

回答

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) 
+0

謝謝!我不知道它不能參數化表格。 –