日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python批量写入数据库engine_python 快速写入postgresql数据库方法

發(fā)布時(shí)間:2023/12/19 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python批量写入数据库engine_python 快速写入postgresql数据库方法 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一種是導(dǎo)入sqlalchemy包,另一種是導(dǎo)入psycopg2包。

具體用法如下(此處以postgre數(shù)據(jù)庫(kù)舉例)

第一種:

# 導(dǎo)入包

from sqlalchemy import create_engine

import pandas as pd

from string import Template

engine = create_engine("oracle://user:pwd@***:***/racdb", echo=False)

# 初始化引擎

engine = create_engine('postgresql+psycopg2://' + pg_username + ':' + pg_password + '@' + pg_host + ':' + str(

pg_port) + '/' + pg_database)

query_sql = """

select * from $arg1

"""

query_sql = Template(query_sql) # template方法

df = pd.read_sql_query(query_sql .substitute(arg1=tablename),engine) # 配合pandas的方法讀取數(shù)據(jù)庫(kù)值

# 配合pandas的to_sql方法使用十分方便(dataframe對(duì)象直接入庫(kù))

df.to_sql(table, engine, if_exists='replace', index=False) #覆蓋入庫(kù)

df.to_sql(table, engine, if_exists='append', index=False) #增量入庫(kù)

注意:上述df.to_sql的方法實(shí)在是太慢太慢了,千萬(wàn)的數(shù)據(jù)chunksize設(shè)置為萬(wàn),上傳了5個(gè)小時(shí) 郁悶。查資料后得知以下方法:速度極快!!!!!

def write_to_table(df, table_name, if_exists='fail'):

import io

import pandas as pd

from sqlalchemy import create_engine

db_engine = create_engine('postgresql://***:***@***:***/***')# 初始化引擎

string_data_io = io.StringIO()

df.to_csv(string_data_io, sep='|', index=False)

pd_sql_engine = pd.io.sql.pandasSQL_builder(db_engine)

table = pd.io.sql.SQLTable(table_name, pd_sql_engine, frame=df,

index=False, if_exists=if_exists,schema = 'goods_code')

table.create()

string_data_io.seek(0)

string_data_io.readline() # remove header

with db_engine.connect() as connection:

with connection.connection.cursor() as cursor:

copy_cmd = "COPY goods_code.%s FROM STDIN HEADER DELIMITER '|' CSV" %table_name

cursor.copy_expert(copy_cmd, string_data_io)

connection.connection.commit()

總結(jié)

以上是生活随笔為你收集整理的python批量写入数据库engine_python 快速写入postgresql数据库方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。