Skip to content

Instantly share code, notes, and snippets.

@limboinf
Forked from damozhang/torndb.ex.py
Last active January 19, 2016 07:11
Show Gist options
  • Save limboinf/184c0080543c125a1799 to your computer and use it in GitHub Desktop.
Save limboinf/184c0080543c125a1799 to your computer and use it in GitHub Desktop.
Examples of that how to use Torndb.
import torndb
mysql_settings = {
'host': 'localhost:3306',
'user': 'user',
'password': 'password',
'database': 'database',
'time_zone': '-8:00',
'charset': 'utf8'
}
# Connect to mysql
db = torndb.Connection(**mysql_settings)
table_name = 'user'
# Insert
def insert(table_name, data):
"""
python2.x
sql = "INSERT INTO %(table_name)s (%(fields)s) values (%(values)s)"
fields = []
values = []
for key, value in data.items():
fields.append(key)
values.append("%(" + key + ")s")
sql = sql % dict(table_name=table_name,
fields=','.join(fields),
values=','.join(values))
"""
# python 3.x
sql = "INSERT INTO %(table_name)s (%(fields)s) values (%(values)s)".format
fields = []
values = []
for key, value in data.items():
fields.append(key)
values.append("%(" + key + ")s")
sql = sql(table_name=table_name,
fields=','.join(fields),
values=','.join(values))
return db.execute(sql, **data)
uid = insert(table_name, {'username': 'david', 'password': 'abc'})
# Select
sql = "SELECT * FROM {table_name} WHERE uid in %(uid)s".format(
table_name=table_name)
query_uid = [1, 2, 3]
rows = db.query(sql, uid=tuple(query_uid)) # rows is a list
sql = "SELECT * FROM {table_name} WHERE uid = %(uid)s".format(
table_name=table_name)
rows = db.get(sql, uid=uid) # rows is a dict
# Update
sql = "UPDATE {table_name} SET password=%(password)s WHERE uid=%(uid)s".format(
table_name=table_name)
db.update(sql, uid=uid, password=password)
# Delete
sql = "DELETE FROM {table_name} WHERE uid=%(uid)s".format(
table_name=table_name)
db.execute(sql, uid=uid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment