python - 将 csv 中的行插入 mysql 数据库

标签 python mysql pymysql

我正在提取给定文件夹中的所有 csv 并尝试将它们逐行插入到 mysql 数据库中。这是我的代码:

def upload_to_db(table, folder):

print('Uploading...', end='')

files = grab_files(folder)

# Connect to dfeventlogger database
connection = pymysql.connect(**eventlogger_config, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:

        # Open each csv in the files list
        # and ignore column headers
        for file in files:
            csv_file = open_csv(file)
            csv_headers = csv_file[0]
            #csv_headers = tuple(csv_file[0]) #tried this too with no luck
            csv_data = csv_file[1:]

            # Insert each row of each csv into eventlogger table
            for row in csv_data:
                placeholders = ', '.join(['%s'] * len(row))
                sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, csv_headers, placeholders)
                print(csv_headers, '\n')
                print(sql, '\n')
                print(row)
                cursor.execute(sql, row)
    # Connection is not autocommit by default.
    # So you must commit to save your changes.
    connection.commit()

finally:
    connection.close()

print('Finished')

upload_to_db('gsSearchAnalyticsTest', 'some_folder')

这是输出:

Uploading...['date', 'site_id', 'site', 'landing_page', 'keyword', 'source', 'impressions', 'clicks', 'position'] 

INSERT INTO gsSearchAnalyticsTest ( ['date', 'site_id', 'site', 'landing_page', 'keyword', 'source', 'impressions', 'clicks', 'position'] ) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s ) 

['2018-01-01', '2', 'something.co.uk', 'something.co.uk/somewhere_in_the_world', 'somewhere in the world', 'uk', '1', '1', '2.000000000000']

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '['date', 'site_id', 'site', 'landing_page', 'keyword', 'source', 'impressions', ' at line 1")

这就是我正在尝试做的事情:

  • 从源数据库中提取数据
  • 导出为 csv 并保存在某个文件夹中
  • 拾取并循环遍历文件夹中的所有 csv 文件并将其插入目标数据库

问题是,我的代码哪里出了问题?我该如何纠正它?

最佳答案

从查询“INSERT INTO gsSearchAnalyticsTest (['date',...]) VALUES (...)”中删除方括号

关于python - 将 csv 中的行插入 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58305797/

相关文章:

python - 无法在 atom 中安装软件包(Ubuntu 17.04)

mysql - 如何在一个表中为另一个表中的每个用户创建一行?

mysql - 从我的计算机加载文件时,访问被拒绝 'root' @'%'

mysql - 如何将 SQL Server 中的唯一数据划分到两台不同的计算机

python - PyMySQL 返回旧/快照值/不重新运行查询?

python - 为什么 ser.readline 数据没有出现在 mysql 中?

python - 部署模型时在azure ml入口脚本中导入数据和python脚本

mysql - 如何使用 group_concat 与基于价格的数量总和?

python - Peewee CompressedField 在 MySQL 数据库上被截断

python - load_iris() 得到了一个意外的关键字参数 'as_frame'