python:读取excel并将其数据插入mysql
程序员文章站
2024-03-23 17:47:04
...
在工作中,经常会遇到需要准备批量的数据,现将基于python语言,读取excel数据并将数据插入数据库表的操作作简单记录:
# coding:utf-8
import pymysql
import xlrd
# 从excel读取数据写入mysql
def excel_to_mysql(filename):
conn = pymysql.connect(host="localhost",user="user",password="pwd",database="连接的数据库名",charset="utf8")
# 连接数据库
cur = conn.cursor()
book = xlrd.open_workbook(filename)
sheet = book.sheet_by_name('Sheet1')
# 获取行数
rows = sheet.nrows
print(rows)
# 将标题之外的其他行写入数据库
for r in range(1, rows):
r_values = sheet.row_values(r)
print(r_values)
sql = "insert into USER(name,age) values(%s,%s);"
# 将每一行插入sql
data = cur.execute(sql,(r_values[0],r_values[1]))
# 插入所有数据后提交
conn.commit()
cur.close()
conn.close()
excel_to_mysql(r"****\USER.xlsx")
下一篇: jq处理div的一些操作及思路
推荐阅读
-
python:读取excel并将其数据插入mysql
-
python读取Excel文件,连接MySQL数据库插入或更新表
-
Python实现读取SQLServer数据并插入到MongoDB数据库的方法示例
-
python读取excel指定列数据并写入到新的excel方法
-
Python3读取Excel数据存入MySQL的方法
-
python3 pandas 读取MySQL数据和插入的实例
-
python读取word文档,插入mysql数据库的示例代码
-
python3+mysql查询数据并通过邮件群发excel附件
-
Python读取excel表格数据并绘制成柱状图 | 数据排序、柱状图颜色、标签乱码等问题通通能够解决!
-
数据库MySql python读取插入数据,insert对那些类型加单引号,表单自己参考自己(外键),空值和NULL