Skip to content

Instantly share code, notes, and snippets.

@damozhang
Created January 28, 2015 20:06
Show Gist options
  • Save damozhang/d6697aabf16dd1037314 to your computer and use it in GitHub Desktop.
Save damozhang/d6697aabf16dd1037314 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):
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