使用pandas进行PostgreSQL的读写

在Arch Linux上安装所需的库文件。

sudo pacman -S python-sqlalchemy

创建数据库

#! /usr/bin/python
#
#	postgre_create.py
#
#					Mar/05/2023
# ------------------------------------------------------------------
import sys
import pandas as pd
#
from sqlalchemy import create_engine
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
df = pd.DataFrame([
		["t1271","千葉",58471,"2003-9-25"],
		["t1272","勝浦",49523,"2003-3-16"],
		["t1273","市原",27461,"2003-6-21"],
		["t1274","流山",39872,"2003-8-27"],
		["t1275","八千代",21576,"2003-11-5"],
		["t1276","我孫子",53271,"2003-1-12"],
		["t1277","鴨川",81326,"2003-5-22"],
		["t1278","銚子",95142,"2003-10-18"]])

#print(df)
#
engine = create_engine('postgresql://scott:tiger123@127.0.0.1/city')
#
#
df.to_sql(name='cities',con=engine,if_exists='replace',index=None)
#
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

读取数据库

#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	postgre_read.py
#
#					Oct/01/2018
# ------------------------------------------------------------------
import sys
import pandas as pd
#
from sqlalchemy import create_engine
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
engine = create_engine('postgresql://scott:tiger123@127.0.0.1/city')
#
df=pd.read_sql_query('SELECT * FROM cities', con=engine)
print(df)
#
df.to_csv("tmp001.csv",header=None,index=None)
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

确认的版本

$ python
Python 3.10.9 (main, Dec 19 2022, 17:35:49) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas
>>> pandas.__version__
'1.5.3'
广告
将在 10 秒后关闭
bannerAds