相关疑难解决方法(0)

如何在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万
查看次数

Python sqlite3参数化drop table

我在python中删除sqlite3表时遇到问题.我正在使用标准sqlite3模块.

self.conn = sqlite3.connect(...)

sql = """ drop table ? """
self.conn.execute( sql, (u'table_name',) )
Run Code Online (Sandbox Code Playgroud)

给我 OperationalError: near "?": syntax error

当我sql改为:

sql = """ drop table table_name """
Run Code Online (Sandbox Code Playgroud)

它工作正常.

python sqlite parameterized-query sql-drop

5
推荐指数
1
解决办法
2154
查看次数

标签 统计

python ×2

mysql ×1

parameterized-query ×1

sql-drop ×1

sqlite ×1