Python写入MySQL数据库的方式有哪些

WBOY
WBOY转载
2023-06-03 12:52:09285浏览

场景一:数据不需要频繁的写入mysql

使用 navicat 工具的导入向导功能。这个软件可以支持多种文件格式,自动根据文件字段建立表格并方便地插入数据,速度也非常快。

Python写入MySQL数据库的方式有哪些

Python写入MySQL数据库的方式有哪些

场景二:数据是增量的,需要自动化并频繁写入mysql

测试数据:csv 格式 ,大约 1200万行

import pandas as pd
data = pd.read_csv('./tianchi_mobile_recommend_train_user.csv')
data.shape

打印结果

Python写入MySQL数据库的方式有哪些

方式一

python + pymysql 库

安装 pymysql 命令

pip install pymysql

代码实现:

import pymysql

# 数据库连接信息
conn = pymysql.connect(
       host='127.0.0.1',
       user='root',
       passwd='wangyuqing',
       db='test01', 
       port = 3306,
       charset="utf8")

# 分块处理
big_size = 100000
# 分块遍历写入到 mysql    
with pd.read_csv('./tianchi_mobile_recommend_train_user.csv',chunksize=big_size) as reader:

    for df in reader:

        datas = []
        print('处理:',len(df))
#         print(df)
        for i ,j in df.iterrows():
            data = (j['user_id'],j['item_id'],j['behavior_type'],
                    j['item_category'],j['time'])
            datas.append(data)
        _values = ",".join(['%s', ] * 5)
        sql = """insert into users(user_id,item_id,behavior_type
        ,item_category,time) values(%s)""" % _values
        cursor = conn.cursor()
        cursor.executemany(sql,datas)
        conn.commit()
 # 关闭服务      
conn.close()
cursor.close()
print('存入成功!')

Python写入MySQL数据库的方式有哪些

方式二

pandas + sqlalchemy:pandas需要引入sqlalchemy来支持sql,在sqlalchemy的支持下,它可以实现所有常见数据库类型的查询、更新等操作。

代码实现:

from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://root:wangyuqing@localhost:3306/test01')
data = pd.read_csv('./tianchi_mobile_recommend_train_user.csv')
data.to_sql('user02',engine,chunksize=100000,index=None)
print('存入成功!')

Python写入MySQL数据库的方式有哪些

以上就是Python写入MySQL数据库的方式有哪些的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除
PHP培训优惠套餐