qst*_*tnr 6 python postgresql sqlalchemy pandas sqlalchemy-utils
我对 Python 很陌生,对使用 postgresql 也很陌生,所以如果这是基本的东西(我 - 到目前为止 - 未能实现),请原谅我。我正在尝试编写一个 python 代码:
testdb
)到目前为止,我有 3 个不同的文件:a)一个.ini
-File,我在其中存储创建新数据库所需的数据库信息,b)一个.csv
-File(来自此处,命名为100_recs.csv
)和 c)我的 python 代码。
数据库.ini :
[postgresql]
host=localhost
user=postgres
password=creator
port=5432
Run Code Online (Sandbox Code Playgroud)
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:
# /sf/ask/2413884651/
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')
Run Code Online (Sandbox Code Playgroud)
当我尝试这样做时,出现以下错误:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError)
但是,当我按照this SO post中的建议进行操作时,它会起作用。不幸的是,在这篇文章中使用的答案psycopg2
创建一个新的数据库,但我想做到这一点的sqlalchemy
(也因为我认为,随着大熊猫工作数据帧进一步上会使用更加简单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'))
Run Code Online (Sandbox Code Playgroud)
但老实说,我被困在这里并需要一些帮助......如果有人能指出我正确的方向,那就太好了。
编辑:啊愚蠢的我!所以我在下面的行中有一个旧的错字db_creator.py
user, host, port = testdb.params['user'], testdb.params['host'], testdb.params['port']
pw = testdb.params['password']
Run Code Online (Sandbox Code Playgroud)
应该:
user, host, port = self.params['user'], self.params['host'], self.params['port']
pw = self.params['password']
Run Code Online (Sandbox Code Playgroud)
我已经改变了这一点。
然后我也忘了在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
Run Code Online (Sandbox Code Playgroud)
编辑 2:
它现在可以使用以下设置:
数据库.ini :
[postgresql]
host=localhost
user=postgres
password=postgres
port=5432
Run Code Online (Sandbox Code Playgroud)
配置文件:
# 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
Run Code Online (Sandbox Code Playgroud)
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:
# /sf/ask/2413884651/
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())
Run Code Online (Sandbox Code Playgroud)
为愚蠢的错误道歉......
psycopg2
只是一个提供适配器以Postgres
使用python
代码连接到数据库的模块。另一方面,SQLAlcehmy
是一个Object Relational Mapper
. 它提供了一个额外的抽象层,将 sql 表镜像到 python 对象,并标准化在代码和数据库之间移动数据的操作。
您可以同时使用psycopg2
和,如文档中所示sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2451 次 |
最近记录: |