我希望使用python将CSV数据添加到MySQL中,但我希望使用csv的列在mysql表中自动创建列。
是否有任何方法可以使用python自动创建MySQL表的列?
发布于 2022-09-09 14:39:13
在MySQL (或任何其他数据库)中创建表的方法之一: PostgreSQL、SQLite、.)基于.csv头(列名)是通过使用熊猫和金炼金术组合而成的。
首先,您需要安装这两个库:
pip install pandas
pip install sqlalchemy考虑到下面的.csv (4列):

其次,通过运行这段代码,您将能够创建一个名为test_table的表,其中包含变量/列表type_cols中定义的类型。
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('mysql://user:password@server/database') #Put here your credentials
df = pd.read_csv('csv_sql.csv') #Change the parameters to match your csv properties
type_cols = ['DATE', 'INTEGER', 'TEXT', 'REAL'] #Put here the columns types
name_cols = df.columns.tolist()
table_config= ', '.join([' '.join(map(str, i)) for i in zip(name_cols, type_cols)])
engine.execute(f'''CREATE TABLE IF NOT EXISTS test_table ({table_config})''')如果有必要,您可以通过运行以下命令来检索数据文件:
df = pd.read_sql("SELECT * FROM test_table", engine) #Change the query to match your needs
print(df)
col1 col2 col3 col4https://stackoverflow.com/questions/73660452
复制相似问题