它使sql文件能够作为python模块导入。
sql-importer的Python项目详细描述
它允许将sql文件作为python模块导入。
要求
- python 2.7版
- python 3.6
安装
$ pip install sql-importer
用法
必须在SQL文件所在的同一目录下创建\uu init\uuu.py。
像下面这样写到.py:
## if using django:# from django.db import connectionimportosfromsql_importerimportinitinit(os.path.dirname(__file__),globals(),connection,sql_type='postgresql')
仅此而已,您可以将sql文件(删除.sql后缀)导入为python模块。
- 示例:
Test/SQL/SuMySalest.SQL。
SELECTSUM(price)ASsum_salesFROMsalesWHEREsales_from>=:'sales_from'ANDsales_to<:'sales_to';
fromdatetimeimportdatefromtestingimportsqlsql.sum_sales.query(sales_from=date(2017,5,22),sales_to=date(2017,12,26))
- sql对象有两个方法,两个方法都执行sql并接收变量作为关键字参数。
query: It returns records. it expects only what has one or more results like select query. execute: It returns number of records affected by the SQL.
- 示例:
现在sql_type参数允许postgresql。
- 如果您想使用另一个sql类型,请在https://github.com/beproud/sql-importer上解决此问题。
演示
启动
$ git clone git@github.com:beproud/sql-importer.git
$ cd sql-importer
$ docker-compose up
准备
$ docker exec -it sqlimporter_app_1 /bin/bash # python -m venv venv # only first time # source venv/bin/activate
尝试
(venv)# ls tests/postgresql/sql __init__.py __init__.pyc __pycache__ clear.sql create_table.sql delete.sql drop_table.sql insert.sql select.sql update.sql (venv)# python
>>>fromtests.postgresqlimportsql>>>sql.sql.clearsql.create_tablesql.drop_tablesql.init(sql.ossql.selectsql.connectionsql.deletesql.hostsql.insertsql.psycopg2sql.update>>>sql.create_table.execute()-1>>>sql.insert.execute(name='apple',price=100)1>>>list(sql.select.query())[{'name':'apple','price':100}]>>>sql.delete.execute(name='orange')0>>>sql.delete.execute(name='apple')1>>>list(sql.select.query())[]
单元测试
(venv)# tox
- 此库仅由最新的PostgreSQL测试。
贡献者
- aodag(https://github.com/aodag)
- crohaco(https://github.com/righ)