【发布时间】:2020-10-30 03:42:08
【问题描述】:
抱歉,这可能是一个简单的问题。我一直在使用 pandas 并且将 excel 文件加载到 MSSQL 中没有问题,但是,我无法为 mysql 弄清楚。我无法下载 MySQLdb 包,所以我安装了 mysql 包并使用了 mysql.connector,如下所示:
原始代码
import pandas as pd
import mysql.connector as mysql
data = pd.read_excel(r"[my file path]")
df = pd.DataFrame(data, columns=['Name', 'country', 'age', 'gender'])
conn = mysql.connect('Driver={SQL Server};'
'Server=[my server name];'
'Database=[my database];'
'Trusted_Connection=yes;')
cursor = conn.cursor()
print(df)
for row in df.itertuples():
cursor.execute('''
INSERT INTO [database].dbo.[table] (Name, country, age, gender)
VALUES (?,?,?,?)
''',
row.Name,
row.country,
row.age,
row.gender
)
conn.commit()
不知道我应该做些什么才能使这一切正常工作。
有效的代码
import mysql.connector
import pandas as pd
conn= mysql.connector.connect(user='[username]', password='[password]', host='[hostname]', database='[databasename]')
cursor = conn.cursor()
excel_data = pd.read_excel(r'[filepath]',sep=',', quotechar='\'')
for row in excel_data.iterrows():
testlist = row[1].values
cursor.execute("INSERT INTO [tablename](Name, Country, Age, Gender)"
" VALUES('%s','%s','%s','%s')" % tuple(testlist))
conn.commit()
cursor.close()
conn.close()
更简洁的代码也可以使用
import pandas as pd
from sqlalchemy import create_engine, types
engine = create_engine('mysql://root:[password]@localhost/[database]') # enter your password and database names here
df = pd.read_excel(r"[file path]",sep=',',quotechar='\'',encoding='utf8') # Replace Excel_file_name with your excel sheet name
df.to_sql('[table name]',con=engine,index=False,if_exists='append') # Replace Table_name with your sql table name
【问题讨论】:
-
您好,您能详细解释一下您目前的问题是什么吗?您已经清楚地解释了您所做的事情,但是从您所写的内容中不清楚症状是什么,您的代码试图实现什么,或者您到底不清楚什么?
-
我正在尝试使用 pandas 将 excel 文件加载到 mysql 数据库中,上面的代码适用于 MSSQL(减去 import mysql;我使用 import pyodbc)但是我不知道如何使它适用于mysql。在这方面寻求帮助。我是否设置了错误的连接?语法错了吗?感谢您的回复!