共计 2370 个字符,预计需要花费 6 分钟才能阅读完成。
使用 Python 来操作数据库,第一时间都会想到 MySQLdb 这个库,但是个人感觉还是 peewee 库比较好用,写出来的代码更加规范、更加优美。这里其他功能就不多讲了,这次以 truncate table 为例子对比下两个库的差异!
使用 MySQLdb 库来连接的例子
#!/usr/bin/python
#-*- coding:utf-8 -*-
#__author__ == ‘chenmingle’
import MySQLdb
mysql_db = {
“name”: “test_db”,
“host”: “127.0.0.1”,
“port”: 3306,
“user”: “root”,
“pswd”: “Password”,
“charset”: ‘utf8’
}
mydb = MySQLdb.connect(host=mysql_db[‘host’],
user=mysql_db[‘user’],
passwd=mysql_db[‘pswd’],
db=mysql_db[‘name’])
cursor = mydb.cursor()
tables = [‘domains_Conf’,’dnspod_Conf’,’jz_domains_Conf’]
## create truncate query
for tab in tables:
sql = ‘truncate table %s’ %(tab)
cursor.execute(sql)
mydb.commit() # execute truncate query
cursor.close()
mydb.close()
print “Table truncated success!”
使用 peewee 库来连接 mysql 例子
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = ‘chenmingle’
from peewee import *
mysql_db = {
“name”: “test_db”,
“host”: “127.0.0.1”,
“port”: 3306,
“user”: “root”,
“pswd”: “Password”,
“charset”: ‘utf8’
}
db = MySQLDatabase(mysql_db[‘name’], host=mysql_db[‘host’], user=mysql_db[‘user’], passwd=mysql_db[‘pswd’],
port=mysql_db[‘port’], charset=mysql_db[‘charset’])
class BaseModel(Model):
class Meta:
database = db
database.get_conn().ping(True)
class DomainsConf(BaseModel):
class Meta:
db_table = “domains_Conf”
dns_id = PrimaryKeyField()
domain_id = IntegerField(index=True)
types = CharField(max_length=64, default=’A’)
hostname = CharField(max_length=64)
line = CharField(max_length=64, default=’default’)
ttl = CharField(max_length=64, default=’600′)
value = TextField()
status = CharField(max_length=32, default=’ENABLE’)
class DNSPODConf(BaseModel):
class Meta:
db_table = “dnspod_Conf”
dns_id = PrimaryKeyField()
type = CharField(max_length=64, default=’A’)
name = CharField(max_length=64)
line = CharField(max_length=64, default=’ 默认 ’)
line_id = CharField(max_length=64, default=’0′)
ttl = CharField(max_length=64, default=’60’)
value = TextField()
status = CharField(max_length=32, default=’1′)
class JZDomainsConf(BaseModel):
class Meta:
db_table = “jz_domains_Conf”
dns_id = PrimaryKeyField()
domain_id = IntegerField(index=True)
types = CharField(max_length=64, default=’A’)
hostname = CharField(max_length=64)
line = CharField(max_length=64, default=’default’)
ttl = CharField(max_length=64, default=’600′)
value = TextField()
status = CharField(max_length=32, default=’ENABLE’)
if __name__ == ‘__main__’:
DomainsConf.truncate_table()
DNSPODConf.truncate_table()
JZDomainsConf.truncate_table()
: