数据库通信管理器
db-commuter的Python项目详细描述
数据库通信管理器
用于与数据库通信的包装器集合。支持以下数据库:
- sqlite
- PostgreSQL
安装
要安装软件包,只需使用pip。
$ pip install db_commuter
sqlite
要创建新的通勤器实例,需要通过构造函数设置sqlite数据库文件的路径。
fromdb_commuter.commutersimportSQLiteCommutercommuter=SQLiteCommuter(path2db)
从表中选择数据并返回pandas数据框。
age=55salary=1000data=commuter.select('select * from people where age > %s and salary > %s'%(age,salary))
从熊猫数据帧插入到数据库表。
commuter.insert('people',data)
执行SQL语句。
who='Yeltsin'age=72commuter.execute('insert into people values (?, ?)',vars=(who,age))
要用一个调用执行多个sql语句,请使用executescript()
。
commuter.execute_script(path2script)
PostgreSQL
设置通勤者
要使用postgresql数据库初始化新的通勤器,需要设置基本的连接参数,这些参数是
host
,port
,user
,password
,db_name
。任何其他连接参数都可以作为关键字传递。
支持的参数列表can be seen here。
fromdb_commuter.commutersimportPgCommutercommuter=PgCommuter(host,port,user,password,db_name,sslmode='require')
或者,可以使用带参数的字典。
params={'host':'localhost','port':'5432','user':'postgres','password':'password','db_name':'test_db'}commuter=PgCommuter(**params)
基本用法
基本操作提供了select()
、insert()
和execute()
方法。
data=commuter.select('select * from people where age > %s and salary > %s'%(55,1000))commuter.insert('people',data)commuter.execute('insert into people values (%s, %s)',vars=('Yeltsin',72))
要使用一个调用执行多个SQL语句,请使用executescript()。
commuter.execute_script(path2script)
快速插入
与insert()
方法相反,该方法反过来使用pandas to_sql()
机器,而insert_fast()
方法
使用postgresqlcopy
命令有效地将pandas数据帧中的数据复制到数据库。
commuter.insert_fast('people',data)
与传统的insert()
方法相比,该方法在处理大型数据帧时更有效。
在构造函数中设置架构
如果只对特定架构中的表进行操作,则可以指定数据库架构的名称 创建通勤实例时。
fromdb_commuter.commutersimportPgCommutercommuter=PgCommuter(host,port,user,password,db_name,schema='model')
许可证
包在MIT License下发布。