如何使用python在循环中创建多个sql表

vbopmzt1  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(494)

所以我写了一个程序来转换我的.csv文件,并将转换后的文件导出到数据库中。csv文件都有相同的列,我试图使用循环创建多个表,我得到了这个错误。
pymysql.err.programmingerror:(1064,“您的sql语法有错误;请检查与您的mariadb服务器版本相对应的手册,以获取要在“”附近使用的正确语法(\n
{}int,\n'在第1行“)
代码:
country\u index=input('国家代码:')
def database\u uploader():

  1. conn = pymysql.connect(host='localhost',
  2. user='test_user',
  3. password='',
  4. db='%s'%country_index)
  5. cur = conn.cursor()
  6. path = r'C:\Users\Robin\Desktop\usa_indicator'
  7. filenames = glob.glob(path + '/*.csv')
  8. dfs = []
  9. for files in filenames:
  10. f = open(files)
  11. fString = f.read()
  12. fName = files[37:2]
  13. for lines in fString.split('\n'):
  14. dfs.append(lines.split(','))
  15. DATE = dfs[0][1]; REALTIME_START = dfs[0][2]; VALUE = dfs[0][3]
  16. queryCreateTable = """CREATE TABLE '%s'(
  17. {} int,
  18. {} int,
  19. {} int
  20. )"""%fName.format(DATE, REALTIME_START, VALUE)
  21. cur.execute(queryCreateTable)
  22. conn.close()
at0kjp5o

at0kjp5o1#

运算符优先级导致 % 以及 .format() 以不同的方式工作。 . 优先级高于 % ,所以它就像你写的一样被执行。

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

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

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

或者您可以只使用一个格式化运算符:

  1. queryCreateTable = """CREATE TABLE `{}`(
  2. `{}` int,
  3. `{}` int,
  4. `{}` int
  5. )""".format(fName, DATE, REALTIME_START, VALUE)

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

展开查看全部

相关问题