【问题标题】:Creating SQL Table with variable name from Python从 Python 创建带有变量名的 SQL 表
【发布时间】:2015-08-08 11:35:44
【问题描述】:

我正在尝试使用 Python 创建 DataFrame 并将其写入 SQL 表。该表应该以一个变量命名,特别是table_nametable_name 将在我运行我的代码时发生变化)。以下是我的代码的相关部分,用于尝试设置:

con = sql.connect(r'/Users/linnk/Desktop/Results/Data.db')  # Creates database to write to
cur = con.cursor() 

...code...

cur.execute('''CREATE TABLE IF NOT EXISTS ''' + table_name + ''' (Date, Morning1, Day1, Evening1, Night1, Morning3, Day3, Evening3, Night3)''')

运行它会给出错误(最后一行):

OperationalError: near "-": syntax error

我尝试对代码的最后一行进行多次修改,但出现了类似的错误。谁能帮我发现我的错误/对我的代码进行必要的调整?有关信息,table_name 包含一个字符串。

提前感谢您的任何建议。

编辑/更新:

根据我的阅读,创建一个然后传递给 cur.execute() 的字符串似乎更好:

   stringexecute='''\'CREATE TABLE IF NOT EXISTS '''+ table_name +''' (Date, Morning1 real, Day1 real, Evening1 real, Night1 real, Morning3 real, Day3 real, Evening3 real, Night3 real)\''''
   cur.execute(stringexecute)

有关信息,stringexecute 输出:

stringexecute= 'CREATE TABLE IF NOT EXISTS GUTUR_400_F1-KIAGA-1 (Date, Morning1Ph real, Day1Ph real, Evening1Ph real, Night1Ph real, Morning3Ph real, Day3Ph real, Evening3Ph real, Night3Ph real)'

但是,代码仍然不起作用。它给出了:

OperationalError: near "'CREATE TABLE ......'": syntax error

任何进一步的帮助将不胜感激。我主要查看并(未成功)尝试了以下资源中的方法: http://www.sommarskog.se/dynamic_sql.html#objectnames https://docs.python.org/2/library/sqlite3.html

编辑

只要变量table_name 不包含“-”(可能还有其他符号),结果如下:

 cur.execute("CREATE TABLE IF NOT EXISTS " + table_name + " (Date, Morning1 real, Day1 real, Evening1 real, Night1 real, Morning3 real, Day3 real, Evening3 real, Night3 real)")

【问题讨论】:

  • 如果硬编码表名会发生什么?
  • 这似乎有效 - 这会在数据库中创建“Table1”:cur.execute('''CREATE TABLE IF NOT EXISTS Table1 (Date, Morning1, Day1, Evening1, Night1, Morning3, Day3,晚上 3,晚上 3)''')
  • 根据您上次的更新,问题似乎只是禁用字符。您可以在执行表创建步骤之前 regex.sub 吗?
  • 我只是使用了 dataframe.replace() 并将 '-' 替换为 '_'

标签: python sql pandas dataframe


【解决方案1】:

你为什么不使用:

cur.execute('CREATE TABLE IF NOT EXISTS {tab} (Date, Morning1, Day1, Evening1, Night1, Morning3, Day3, Evening3, Night3)'
   .format(tab=table_name))

【讨论】:

    【解决方案2】:

    输入这段代码:

    def crear_tabla (name):
    cur = conn.cursor()
    cur.execute('''CREATE TABLE {tab}
      (ID INT PRIMARY KEY     NOT NULL,
      NAME           TEXT    NOT NULL,
      AGE            INT     NOT NULL,
      ADDRESS        CHAR(50),
      SALARY         REAL);'''.format(tab=name))
    print ("Table created successfully")
    cur.close()
    conn.commit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 2017-10-12
      相关资源
      最近更新 更多