【问题标题】:How to create multiple sql tables in a loop with python如何使用python在循环中创建多个sql表
【发布时间】:2018-09-18 20:51:41
【问题描述】:

所以我正在编写这个程序来转换我拥有的 .csv 文件,然后将转换后的文件导出到数据库。 .csv 文件都有相同的列,我正在尝试使用循环创建多个表,但出现此错误。

pymysql.err.ProgrammingError: (1064, "你的 SQL 有错误 句法;检查与您的 MariaDB 服务器相对应的手册 在 '''(\n
{} int,\n ' 在第 1 行")

代码:

country_index = input('国家代码:')

def database_uploader():

  conn = pymysql.connect(host='localhost',
                         user='test_user',
                         password='',
                         db='%s'%country_index)
  cur = conn.cursor()

  path = r'C:\Users\Robin\Desktop\usa_indicator'
  filenames = glob.glob(path + '/*.csv')
  dfs = []
  for files in filenames:
        f = open(files)
        fString = f.read()
        fName = files[37:2]

        for lines in fString.split('\n'):

              dfs.append(lines.split(','))

              DATE = dfs[0][1]; REALTIME_START = dfs[0][2]; VALUE = dfs[0][3]



              queryCreateTable = """CREATE TABLE '%s'(
                                    {} int,
                                    {} int,
                                    {} int
                                    )"""%fName.format(DATE, REALTIME_START, VALUE)

              cur.execute(queryCreateTable)

  conn.close()

【问题讨论】:

  • 你为什么混合%.format()
  • 表名不能用单引号。见stackoverflow.com/questions/11321491/…
  • DATE = dfs[0][1]; REALTIME_START = dfs[0][2]; VALUE = dfs[0][3] 将在每次循环中使用相同的值。你为什么不使用lines 的当前值进行该迭代?
  • 我正在循环浏览我希望我的表格使用的名称。所以我使用 %s 和我的变量来为它们分配这些值。我确定它与 .format 有关系,但我不知道如何分配表名。
  • 日期等是列名。我不知道如何分配除 .format() 方法以外的列名

标签: mysql loops for-loop syntax-error pymysql


【解决方案1】:

运算符优先级导致%.format() 的混合使用与预期不同。 . 的优先级高于 %,所以它的执行就像你写的一样。

         queryCreateTable = """CREATE TABLE '%s'(
                                {} int,
                                {} int,
                                {} int
                                )"""%(fName.format(DATE, REALTIME_START, VALUE))

您需要添加括号来覆盖此解析:

         queryCreateTable = ("""CREATE TABLE '%s'(
                                {} int,
                                {} int,
                                {} int
                                )"""%fName).format(DATE, REALTIME_START, VALUE)

或者你可以只使用一个格式化操作符:

         queryCreateTable = """CREATE TABLE `{}`(
                                `{}` int,
                                `{}` int,
                                `{}` int
                                )""".format(fName, DATE, REALTIME_START, VALUE)

另外,表名和列名应该用反引号,而不是单引号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多