python操作mysql,基本的curd操作,连贯操作,基于MySQLdb。如果语句复杂可以执行原生sql语句。
python2.7.6,需要安装MySQLdb
from Db import mysql
test_db = {"host": "localhost", "user": "root", "passwd": "123456", "db": "dev", "port": "3306", "charset": "utf8"}
# 默认端口是3306,默认编码是utf-8。可以不指定,更多配置信息参考MySQLdb
mysql = mysql(**test_db)
# OR
# mysql = mysql(host='localhost', user='root', passwd='123456', db='dev', port='3306', charset='utf8')
所有操作都必须调用table()
print mysql.table("test").selectOne()
print mysql.table("test").where("name='asd'").selectALl()
print mysql.table("test").selectAll('name')
mysql.table("test").where("name='asd'").update("point=100")
# data为数据关联的dict
data = {"name": "John", "point": 98}
mysql.table("test").table("test").insert(data)
# data为数据关联的list
data = [{"name": "Lilei", "point": 69}, {"name": "xiaohong", "point": 58}]
mysql.table("test").insert_batch(data)
mysql.table("test").delete()
print mysql.table("test").limit(0,10).selectAll()
# 转化为mysql语句为
# SELECT * FROM test WHERE 1=1 LIMIT 0, 10;
print mysql.table("test").order('point desc').selectAll()
# 转化为mysql语句为
# SELECT * FROM test WHERE 1=1 ORDER BY point DESC;
mysql.query("SELECT * FROM test WHERE name = 'asd' ")