Package: ezrecords
ezrecords is a very simple, but powerful, library for making raw SQL
queries to most relational databases.ezrecords = Kenneth Reitz’srecords+ Justin Vincent’sezsql+ WordPress’wpdb-SQLAlchemy.Just write SQL. No bells, no whistles. This common task can be
surprisingly difficult with the standard tools available.
This library strives to make this workflow as simple as possible,
while providing an elegant interface to work with your query results.Database support includes SQLite, Postgres, and MySQL (drivers not included).Why?recordsis awesomeezsqlandwpdbhave very nice API, so it makes for an easy transition
from PHP to PythonOur love for crafting well written and performant SQL queries is not questionable,
but I think a few helpers for some basic DML and recurring queries would help“The ORM takes two brilliant ideas and incapacitates them both.”,
said a very wise man. So, as long as possible I want to keep away from
sqlalchemy or the like.UsageAPIimportloggingfromezrecords.mysqldbimportMySQLDblogger=logging.getLogger()# connectdb=MySQLDb(db_url="mysql://root:passwd@127.0.0.1:3306/test",logger=logger)# logger is optional# enable debugging - optionaldb.save_queries=True# save queries and execution timedb.show_sql=True# show SQL code being executed. logger above is required for logging to workdb.show_errors=True# show errorscreate_user_table="""
CREATE TABLE test_user (
    id INT AUTO_INCREMENT NOT NULL,
    username varchar(255) UNIQUE,
    password varchar(255),
    created_at TIMESTAMP,
    created_at_gmt TIMESTAMP,
    PRIMARY KEY(id)
)
"""db.query(create_table)# run generic SQLcreate_numbers_table="""
DROP TABLE IF EXISTS numbers;
CREATE TABLE numbers(
    ints int,
    floats float
);
"""db.query(create_table_sql)insert_numbers_sql="INSERT INTO numbers (ints, floats) VALUES (%d,%f)"# DB API only accepts %s, so we replace %d and %f by %s internallydb.query(insert_numbers_sql,3,3.14)# run generic queries with params# insert recordsdb.insert('test_user',username='scott',password='tiger',created_at=datetime.datetime.now())db.insert('test_user',{'username':'JONES','password':'STEEL'})# bulk_insert recordsdb.bulk_insert('test_user',('username','password'),[('scott','tiger'),('JONES','STEEL')])# Update recordsdb.update('test_user',{'password':'shepard'},{'username':'scott'})# Delete recordsdb.delete('test_user',{'username':None})# None is converted to NULL# Sanitize querydb.prepare("""INSERT INTO postmeta (post_id, meta_key, meta_value) VALUES ( '%d', "%s",%%s )')""",10,"Harriet's Adages","WordPress' database interface is like Sunday Morning: Easy.")# Call stored proceduresdb.call_procedure('adds',1,2)# Get single variable/valuedb.get_var('SELECT version()')# Get specific row from many resultsdb.get_row('SELECT * FROM test_user',row_offset=1)# if offset not given the first row is returned# Get specific column from many resultsdb.get_col('SELECT username, password FROM test_user',column_offset='password')# offset can be numeric too# Get results in specific formatdb.get_results('SELECT username, password FROM test_user','json')# Get last inserted ID from AUTO_INCREMENT/SERIAL fieldsdb.insert('test_user',username='scott',password='tiger',created_at=datetime.datetime.now())db.last_insert_id# Get number of affected rows from previus querydb.delete('test_user')db.affected_rows# Switch to another databasedb.use('information_schema')# Check query timing# execute long running querydb.last_query_elapsed_time# Transactions# ---db.begin_transaction()db.commit()# or db.rollback()# Data exportrows=db.query('SELECT * FROM table')rows.datasetrows.export('csv')# yaml, json, xls, xlsx# Goodiesdb.db_version()# get server versiondb.exists('table')# check if table existsdb.get_table_names()# get list of tables in databasedb.flush()# clear cache resultsCLIezrecords-hezrecords"SELECT version() AS version""json"--url="mysql://root:passwd@127.0.0.1:3306/test"ezrecords"SELECT version() AS version""json"--url="postgres://postgres:passwd@127.0.0.1:5432/test"ezrecords"SELECT sqlite_version() AS version""json"--url="sqlite:///:memory:"Thank youThanks for checking this library out! I hope you find it useful.Of course, there’s always room for improvement. Feel free toopen an issueso we can makeezrecordsbetter, faster, and stronger.Download and InstallUntil the module is made available on pypi, you can install this module
directly from github with:pip install-egit+https://github.com/dareenzo/ezrecords@master#egg=ezrecordsezrecords runs withPython 2.7 and 3.5.Documentation Generation# edit documentation in _docscd_docsmakesinglehtmlcd..cp-fR_docs/_build/singlehtml/*docs/Copyright & LicenseCode and documentation are available according to the MIT License.See theLICENSEfile for details.# Change logFor a complete view of all the releases, visit the releases page on GitHub:
[https://github.com/dareenzo/ezrecords/releases](https://github.com/dareenzo/ezrecords/releases)## v0.3.0 - 2018-05-12Features:Added support for SQLite## v0.2.0 - 2017-05-27Features:Bulk insert:db.bulk_insert(‘test_user’, (‘username’, ‘password’), [(‘scott’, ‘tiger’), (‘JONES’, ‘STEEL’)])Fixes:Improve documentationUpdate base records library codeFixes error with getting passing params to querystart unquoting username and password as defined in the standard RFC## v0.1.0 - 2017-01-07Initial release