我对 Python 很陌生,对使用 postgresql 也很陌生,所以如果这是基本的东西(我 - 到目前为止 - 未能实现),请原谅我。我正在尝试编写一个python代码:
- 创建一个新数据库 (
testdb
) - 将 csv 文件读入 pandas 数据帧
- 从 pandas 数据框中创建并填充数据库中的新表。
到目前为止,我有 3 个不同的文件:a)一个.ini
-File 用于存储创建新数据库所需的数据库信息,b)一个.csv
-File(从这里命名100_recs.csv
)和 c)我的 python 代码。
数据库.ini:
[postgresql]
host=localhost
user=postgres
password=creator
port=5432
db_creator.py:
from config import config
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
import pandas as pd
# useful info for psycopg2:
# https://stackoverflow.com/questions/34484066/create-a-postgres-database-using-python
class MyDB(object):
def __init__(self):
self.params = config()
def create_new_db(self, newdb):
user, host, port = self.params['user'], self.params['host'], testdb.params['port']
pw = self.params['password']
url = 'postgresql://{}:{}@{}:{}/{}'
url = url.format(user, pw, host, port, newdb)
engine = create_engine(url)
if not database_exists(engine.url):
create_database(engine.url)
print(database_exists(engine.url))
if __name__ == '__main__':
testdb = MyDB()
testdb.create_new_db('testdb')
当我尝试这样做时,我收到以下错误:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError)
但是,当我按照此 SO post中的建议进行操作时,它会起作用。不幸的是,这篇文章中的答案psycopg2
用于创建一个新的数据库,但我想这样做sqlalchemy
(也是因为我认为进一步使用 Pandas 数据框会更容易sqlalchemy
(如这里所示。或者我错了吗?) .我认为,当这样做时,sqlqlchemy
应该可以将csv文件中的数据读取到pandas数据框中,然后在新数据库中填充一个表:
def connect_alchemy(user, host, port, db, password):
url = 'postgresql://{}:{}@{}:{}/{}'
url = url.format(user, password, host, port, db)
con = sqlalchemy.create_engine(url, client_encoding='utf8')
mydata = pd.read_csv('100_recs.csv', delimiter=';', quotechar='"')
data_db = mydata.to_sql(name='100_records', con=con, if_exists='replace', index=True, chunksize=10)
print(con.execute('SELECT * from 100_records'))
但老实说,我被困在这里需要一些帮助......如果有人能指出我正确的方向,那就太好了。
编辑:啊愚蠢的我!所以我在以下几行中有一个旧错字db_creator.py
user, host, port = testdb.params['user'], testdb.params['host'], testdb.params['port']
pw = testdb.params['password']
应该:
user, host, port = self.params['user'], self.params['host'], self.params['port']
pw = self.params['password']
我已经改变了这个。
然后我也忘了在config.py
这里添加文件。对此表示歉意。
干得好:
配置文件
# source: http://www.postgresqltutorial.com/postgresql-python/connect/
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
编辑 2:
它现在适用于以下设置:
数据库.ini:
[postgresql]
host=localhost
user=postgres
password=postgres
port=5432
配置文件:
# source: http://www.postgresqltutorial.com/postgresql-python/connect/
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
csv 文件:从这里
db_creator.py
from config import config
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
import pandas as pd
# useful info for psycopg2:
# https://stackoverflow.com/questions/34484066/create-a-postgres-database-using-python
class MyDB(object):
def __init__(self):
self.params = config()
def create_new_db(self, newdb):
user, host, port = self.params['user'], self.params['host'], self.params['port']
pw = self.params['password']
url = 'postgresql://{}:{}@{}:{}/{}'
url = url.format(user, pw, host, port, newdb)
self.engine = create_engine(url, client_encoding='utf8')
if not database_exists(self.engine.url):
create_database(self.engine.url)
# print(database_exists(engine.url))
def df2postgres(engine, df):
con = engine.connect()
df.to_sql(name='records', con=con, if_exists='replace', index=True, chunksize=10)
return con
if __name__ == '__main__':
testdb = MyDB()
testdb.create_new_db('testdb')
engn = testdb.engine
df = pd.read_csv('100_recs.csv', delimiter=';', quotechar='"', encoding='utf-8')
con = df2postgres(engine=engn, df=df)
dta = con.execute('SELECT * FROM records LIMIT 5;')
print(dta.fetchall())
为愚蠢的错误道歉...