下面是使用Python读取CSV文件快速插入数据库的攻略,具体步骤如下:
步骤一:安装Python数据库驱动
使用Python进行数据库操作需要安装相应的数据库驱动。在本次攻略中,我们将使用MySQL数据库,因此需要安装MySQL数据库驱动。这里我们采用PyMySQL,执行以下命令进行安装:
pip install pymysql
步骤二:准备CSV数据
准备好要插入数据库的CSV文件,确保CSV文件数据与数据库表结构一致。这里我们以Suppliers表为例,创建Suppliers.csv文件并添加数据:
supplier_name,contact_name,email,country
Suppliers Inc.,John Doe,john@suppliers.com,USA
Globex Corporation,Nick Smith,nick@globex.com,UK
步骤三:编写Python代码
接下来,我们编写Python代码实现读取CSV文件并插入MySQL数据库。代码如下:
import csv
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='123456',
db='test', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
try:
# 通过cursor创建游标
with db.cursor() as cursor:
# 读取CSV文件
with open('Suppliers.csv', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
# 遍历CSV文件
for row in reader:
# 插入数据
sql = "INSERT INTO Suppliers (supplier_name, contact_name, email, country) VALUES (%s,%s,%s,%s)"
cursor.execute(sql, (row['supplier_name'], row['contact_name'], row['email'], row['country']))
# 提交到数据库执行
db.commit()
finally:
# 关闭数据库连接
db.close()
示例一:读取供应商列表并插入数据库
假设我们有一个供应商列表,名为Suppliers.csv,内容如步骤二所示。我们执行以下python代码读取该CSV文件并插入数据库:
import csv
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='123456',
db='test', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
try:
# 通过cursor创建游标
with db.cursor() as cursor:
# 读取CSV文件
with open('Suppliers.csv', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
# 遍历CSV文件
for row in reader:
# 插入数据
sql = "INSERT INTO Suppliers (supplier_name, contact_name, email, country) VALUES (%s,%s,%s,%s)"
cursor.execute(sql, (row['supplier_name'], row['contact_name'], row['email'], row['country']))
# 提交到数据库执行
db.commit()
finally:
# 关闭数据库连接
db.close()
示例二:读取订单列表并插入数据库
假设我们有一个订单列表,名为Orders.csv,内容如下:
order_number,product_id,quantity,price,customer_name,customer_email,country
1,1001,2,100.00,John Doe,john@test.com,USA
2,1002,3,200.00,Jim Smith,jim@test.com,Canada
3,1003,4,300.00,Jack Johnson,jack@test.com,UK
我们执行以下python代码读取该CSV文件并插入数据库:
import csv
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='123456',
db='test', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
try:
# 通过cursor创建游标
with db.cursor() as cursor:
# 读取CSV文件
with open('Orders.csv', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
# 遍历CSV文件
for row in reader:
# 插入数据
sql = "INSERT INTO Orders (order_number, product_id, quantity, price, customer_name, customer_email, country) VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (row['order_number'], row['product_id'], row['quantity'], row['price'], row['customer_name'], row['customer_email'], row['country']))
# 提交到数据库执行
db.commit()
finally:
# 关闭数据库连接
db.close()
以上就是使用Python读取CSV文件快速插入数据库的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:使用python读取csv文件快速插入数据库的实例 - Python技术站