简体   繁体   English

如何使用 Python 从 CSV 文件在 MySQL 中创建列名?

[英]How to create columns names in MySQL using Python from CSV file?

I usually work with large CSV data sets.我通常使用大型 CSV 数据集。 Opening these files take a hell lot of time.打开这些文件需要很多时间。 My plan is to directly load the csv files without accessing them but am getting an error while creating the table to load the data.我的计划是直接加载 csv 文件而不访问它们,但是在创建表以加载数据时出现错误。

import string
import csv
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="password")
mycursor = mydb.cursor()
with open(r"C:\Users\rcsid\Documents\Office Programs\Working prog\MOCK_DATA.csv") as csvfile:
    csv_reader = csv.DictReader(csvfile)
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'create table rd.data ( {" varchar(50), ".join(row)} varchar(50))')
            mycursor.execute(f'create table rd.data ( {" varchar(50), ".join(row)}) varchar(50))')
            line_count += 1
        line_count += 1

The print statement is giving the following results:打印语句给出以下结果:

create table rd.data ( id varchar(50), first_name varchar(50), last_name varchar(50), email varchar(50), boole varchar(50), coin varchar(50))创建表 rd.data ( id varchar(50), first_name varchar(50), last_name varchar(50), email varchar(50), boole varchar(50), coin varchar(50))

The above statement seems correct But the execute statement is throwing an error:上面的语句似乎是正确的,但是执行语句抛出了一个错误:

ProgrammingError: 1064 (42000): You have an error in your SQL syntax; ProgrammingError: 1064 (42000): 你的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near ') varchar(50))' at line 1检查与您的 MySQL 服务器版本相对应的手册,以了解在第 1 行的“) varchar(50))”附近使用的正确语法

This is the starting part.这是开始的部分。 The full program will have many other checks.完整的程序将有许多其他检查。 Wanted to know how to solve this error?想知道如何解决这个错误? PS: New to Python PS:Python新手

I was able to resolve this by creating a string statement:我能够通过创建一个字符串语句来解决这个问题:

sql_str=f'create table rd.data ( {" varchar(50), ".join(row)} varchar(50))'
mycursor.execute(sql_str)

This resolved the issue.这解决了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM