Python连接数据库的两种方式

使用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()

相关推荐