可以使用pandas和MySQLdb两个库来实现。

首先需要安装pandas和MySQLdb库:

pip install pandas
pip install MySQLdb

然后,可以按照以下步骤将xlsx文件导入MySQL数据库中的一个表中:

  1. 使用pandas读取xlsx文件数据:
import pandas as pd

data = pd.read_excel('data.xlsx')
  1. 连接MySQL数据库:
import MySQLdb

db = MySQLdb.connect(host='localhost', user='root', passwd='password', db='database_name')
cursor = db.cursor()
  1. 创建表:
sql = '''CREATE TABLE IF NOT EXISTS table_name (
         column1 datatype,
         column2 datatype,
         ...
         )'''
cursor.execute(sql)
  1. 将数据写入MySQL数据库表中:
for i, row in data.iterrows():
    sql = f"INSERT INTO table_name (column1, column2, ...) VALUES ('{row['column1']}', '{row['column2']}', ...)"
    cursor.execute(sql)
db.commit()

注意:

  • 要根据实际情况修改主机名、用户名、密码、数据库名、表名、列名和数据类型等参数。
  • 如果数据中包含特殊字符,可能会出现SQL注入等安全问题,建议使用参数化查询或转义字符来避免这些问题
怎么用python将xlsx文件导入mysql数据库中的一个表中

原文地址: https://www.cveoy.top/t/topic/e8ii 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录