简体   繁体   English

用变量名写入SQLite表(Python)

[英]Writing to SQLite tables with variable names (Python)

I'm trying to write five variables to tables in a database using SQLite and Python. 我正在尝试使用SQLite和Python将五个变量写入数据库中的表。 Below is my code and the error I'm getting: 以下是我的代码和出现的错误:

CODE: 码:

        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))

ERROR on the last line: 最后一行错误:

TypeError: 'str' object is not callable TypeError:“ str”对象不可调用

I've made sure that none of the export_... variables contain strings, so the string must be relevant_table . 我确保export_...变量都不包含字符串,因此该字符串必须为relevant_table However, creating a table using a string variable (see code above again) worked fine so I don't understand why it's giving this error now. 但是,使用字符串变量创建表(再次参见上面的代码)工作正常,所以我不明白为什么现在会出现此错误。

Any input would be greatly appreciated. 任何投入将不胜感激。 Let me know if any additional information would be useful. 让我知道是否还有其他有用的信息。

EDIT : 编辑

Here is my traceback, gotten using traceback.format_exc(): 这是我的追溯,是使用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'

FINAL EDIT, RESOLVED: 最终编辑,已解决:

For information, thanks to scytale, this now works, using: 有关信息,感谢scytale,现在可以使用:

cur.execute("INSERT INTO " + relevant_table + " VALUES (?,?,?,?,?)", (export_date, export_morning, export_day, export_eve, export_night))

I thought I had tried changing the punctuation and spacing in all ways possible, but this finally did the trick. 我以为我已经尝试过以所有可能的方式更改标点和间距,但这终于成功了。

you're missing a comma in your last line after the SQL string - it should be 您在SQL字符串后的最后一行中缺少逗号-应该是

cur.execute("INSERT INTO " + relevant_table + "VALUES (?,?,?,?,?)",
            (export_date, export_morning, export_day, export_eve, export_night))

Really, for clarity and future maintenance you should be specific as to what and where you are inserting. 确实,为清楚起见和将来的维护,您应该具体说明插入的内容和位置。 So your statement should read something like this, for example: 因此,您的语句应显示如下内容:

    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)

This makes it clear, not only what the data items are but where you are putting them. 这不仅使您清楚数据项是什么,还使您知道将它们放在何处。
A good reason for declaring what you are inserting explicitly, is that should you add columns to the table at a later date, then the code will still work as expected. 明确声明要插入的内容的一个很好的理由是,如果您以后要向表中添加列,则代码仍将按预期工作。

As a side note, has everyone forgotten the power of the print statement when it comes to debugging? 附带说明一下,在调试方面,每个人都忘记了print语句的功能吗?
Got a problem? 有问题吗? PRINT the damned stuff out and look at it!! 打印出该死的东西,看看吧! 9 times out of ten it's obvious. 十分之九十分明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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