[英]Writing to SQLite tables with variable names (Python)
我正在尝试使用SQLite和Python将五个变量写入数据库中的表。 以下是我的代码和出现的错误:
码:
cur.execute("CREATE TABLE IF NOT EXISTS " + table_name + " (Date real, Morning_5AM_9AM real, Day_9AM_6PM real, Evening_6PM_10PM real, Night_10PM_5AM real)") # this works
export_row= p_transpose.iloc[ii] # Note: p_transpose is the transpose of a DataFrame I read in from Excel
date_object= p_transpose.iloc[ii,0] # date_object is a string here
date_object= date_object.replace('_','')
export_date= int(date_object) # to insert into database table as int instead of string
export_morning= p_transpose.iloc[ii,1]
export_day= p_transpose.iloc[ii,2]
export_eve= p_transpose.iloc[ii,3]
export_night= p_transpose.iloc[ii,4]
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
available_tables=[item[0] for item in cur.fetchall()] # assigns a list of all table names in database
for iii in range (0, row_count):
if (re.match('\w*'+df_feeder, available_tables[iii])):
relevant_table= available_tables[iii]
cur.execute("INSERT INTO " + relevant_table + "VALUES (?,?,?,?,?)" (export_date, export_morning, export_day, export_eve, export_night))
最后一行错误:
TypeError:“ str”对象不可调用
我确保export_...
变量都不包含字符串,因此该字符串必须为relevant_table
。 但是,使用字符串变量创建表(再次参见上面的代码)工作正常,所以我不明白为什么现在会出现此错误。
任何投入将不胜感激。 让我知道是否还有其他有用的信息。
编辑 :
这是我的追溯,是使用traceback.format_exc()获得的:
'Traceback (most recent call last):\n File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/idlelib/run.py", line 112, in main\n seq, request = rpc.request_queue.get(block=True, timeout=0.05)\n File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/Queue.py", line 176, in get\n raise Empty\nEmpty\n'
最终编辑,已解决:
有关信息,感谢scytale,现在可以使用:
cur.execute("INSERT INTO " + relevant_table + " VALUES (?,?,?,?,?)", (export_date, export_morning, export_day, export_eve, export_night))
我以为我已经尝试过以所有可能的方式更改标点和间距,但这终于成功了。
您在SQL字符串后的最后一行中缺少逗号-应该是
cur.execute("INSERT INTO " + relevant_table + "VALUES (?,?,?,?,?)",
(export_date, export_morning, export_day, export_eve, export_night))
确实,为清楚起见和将来的维护,您应该具体说明插入的内容和位置。 因此,您的语句应显示如下内容:
try:
result = self.db.execute("insert into Recent (Filename,TimeStamp,Icon) values (?,?,?)",(filename,time_stamp,itype))
except sqlite3.Error as e:
wx.MessageBox('Insert Recent file list error'+str(e), 'Error', wx.OK | wx.ICON_INFORMATION)
这不仅使您清楚数据项是什么,还使您知道将它们放在何处。
明确声明要插入的内容的一个很好的理由是,如果您以后要向表中添加列,则代码仍将按预期工作。
附带说明一下,在调试方面,每个人都忘记了print语句的功能吗?
有问题吗? 打印出该死的东西,看看吧! 十分之九十分明显。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.