简体   繁体   中英

Python mysql create and name new table using variable name

So I have variable named 'racenumber' that I want to use as the name of a new table I'm creating.

The python code below is currently not working. Any ideas on where the issue is?

racenumber = 10

cursor = db.cursor()
cursor.execute("""CREATE TABLE %s (ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(50) DEFAULT NULL,    
PRIZE_TOTAL VARCHAR(50) DEFAULT NULL, STRENGTH VARCHAR(50) DEFAULT NULL, URL VARCHAR(50) DEFAULT  
NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1""" % (racenumber))

db.commit()
db.close()

Since you are using a number for the table name, you need to use back-ticks around table name. I tested an example using SQL Fiddle here: http://sqlfiddle.com/#!2/c38e57

racenumber = 10

cursor = db.cursor()
cursor.execute("""CREATE TABLE `%s` (ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(50) DEFAULT NULL,    
PRIZE_TOTAL VARCHAR(50) DEFAULT NULL, STRENGTH VARCHAR(50) DEFAULT NULL, URL VARCHAR(50) DEFAULT  
NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1""" % (racenumber))

db.commit()
db.close()

Here is the link from documentation: http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

Specifically this line:

Identifiers may begin with a digit but unless quoted may not consist solely of digits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM