【问题标题】:import SQL tables from database into Pandas Dataframe without knowing the whole name of the tables在不知道表的全名的情况下将 SQL 表从数据库导入 Pandas Dataframe
【发布时间】:2021-06-02 07:15:05
【问题描述】:

我有一些可能很容易做的事情,但我暂时没有找到确切的答案。我想使用 python 和 sqlite 将数据库中的多个表导入 Spyder。我有一个 target_unique 列表,其中包含特定的目标,如肺、tum 等,但我不应该知道所有目标,这就是为什么我只想写一些简单的东西,比如像 target+'_ref_seg_table' 这样的变量+字符串名称,但我不知道是否在 SQL 查询中是可能的。我的列表 target_unique 在 Spyder 中而不是在数据库中。这是我在其他不起作用的代码中基本上尝试过的。

if largest: # If the latest version of InventoryDB exist (DB with the highest number)
    #print("largest exist")
    #version+=1
    conn2 = sqlite3.connect(largest) # we connect to this latest version of InventoryDB
    cur2 = conn2.cursor()
    for target in target_unique:
        vars()[target+'_ref_seg_table_previous'] = pd.read_sql_query("SELECT * FROM"+ target+"_ref_seg_table", conn2)

也许我应该转移数据库中唯一的列表目标才能使用 target+'ref_seg_table' ? 而且我想我这里不需要vars(),我之前只是用它来创建当前表target+'ref_seg_table',但是对于以前的表我认为我不需要它。 我也尝试使用正则表达式来选择正确的表,但仍然无法正常工作......

提前感谢您的帮助!

【问题讨论】:

    标签: python sql pandas sqlite


    【解决方案1】:

    最后我找到了一种方法,如果它可以帮助我在这里发布它的其他人:

    if largest: # If the latest version of InventoryDB exist (DB with the highest number)
        #print("largest exist")
        #version+=1
        conn2 = sqlite3.connect(largest) # we connect to this latest version of InventoryDB
        cur2 = conn2.cursor()
        # sql query to count how much tables named Series_table there are in the latest version of InventoryDB
        cur2.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='Series_table' ''') 
        
        for target in target_unique: # For each target in model table
        # We import manual cols from ref seg tables from the latest InventoryDB available and we store them as target_ref_seg_table_previous
            vars()[target+'_ref_seg_table_previous'] = pd.read_sql_query("SELECT mycolumns FROM {}_ref_seg_table".format(target),conn2)
            
    

    我刚刚使用了.format!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 2020-10-12
      相关资源
      最近更新 更多