-
-
Save limboinf/184c0080543c125a1799 to your computer and use it in GitHub Desktop.
Examples of that how to use Torndb.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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