小编ext*_*ter的帖子

如何在Python中使用变量名创建mysql表?

我尝试使用Python MySQLdb 执行表变量一文作为示例,但到目前为止还没有什么乐趣。我正在尝试创建一个表,其名称是“archive”和作为变量传递的年份的串联。这是硬编码表名称(例如“archive_2013”​​)的替代方案。

这是我的代码片段:

year_string = sys.argv[1]
if int(year_string) < 1999 or int(year_string) > 2014:
    print "\n"
    print "Year must be between 1999 and 2014\n"
    sys.exit(1)    

table_name = "archive_" + year_string

# Open database connection
db = MySQLdb.connect("localhost","root","menagerie","haiku_archive" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Create table using execute() method.

sql = ""CREATE TABLE IF NOT EXISTS %s" % table_name
      haiku_text VARCHAR(120), 
      date_written CHAR(22))"
cursor.execute(sql)
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误:

pablo@desktop=> ./insert_haiku_from_file_into_table.py 2013 qwert.txt
  File "./insert_haiku_from_file_into_table.py", …
Run Code Online (Sandbox Code Playgroud)

python mysql

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

mysql ×1

python ×1