当且仅当它不存在时,如何创建TABLE?

时间:2010-10-29 18:10:41

标签: python mysql mysql-error-1064

我正在尝试

conn = MySQLdb.connect (host = "localhost",
                           user = "username",
                           passwd = "password",
                           db = "my_db")
cursor = conn.cursor ()
q = """IF NOT EXISTS CREATE TABLE %s (
         course  VARCHAR(15),
         student  VARCHAR(15),
         teacher VARCHAR(15),
         timeslot VARCHAR(15))""" % (d,)

cursor.execute(q)

但我收到错误:_mysql_exceptions.ProgrammingError: (1064, "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 'IF NOT EXISTS CREATE TABLE ACCOUNTG (\\n\\t course VARCHAR(15),\\n\\t s' at line 1")

我不确定我正在尝试的是什么问题,我只想制作一张表,如果它不存在的话。任何意见都将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:14)

语法错误:IF NOT EXISTS CREATE TABLE在MySQL中不是有效的SQL。

你想要

CREATE TABLE IF NOT EXISTS [tablename]

符合MySQL documentation