所以我正在编写这个程序来转换我拥有的.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()
的混合使用与您预期的不同。 .
的优先级高于%
,所以它的执行就像你写的一样。
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)
此外,表和列名称应该是反引号,而不是单引号。