MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0。

自己封装MySQLdb,使操作更加方便些

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# -*- encoding: utf-8 -*-

import MySQLdb

class DB(object):
def __init__(self):
self.host = ''
self.port = int()
self.user = ''
self.passwd = ''
self.db = ''

self.charset = "utf8"
self.conn = None
self.cursor = None

def set(self, host, user, passwd, dbname, port):
self.host = host
self.user = user
self.passwd = passwd
self.db = dbname
self.port = int(port)

def open(self):
self.conn = MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.db,port=self.port,charset=self.charset)
self.cursor = self.conn.cursor()

def execute(self, sql):
count = self.cursor.execute(sql)
return count

def execute(self, sql, values):
count = self.cursor.execute(sql, values)
return count

def sql(self, sql):
self.cursor.execute(sql)
return self.cursor.fetchall()

def commit(self): #插入数据需要执行一次commit才能更新进入数据库
self.conn.commit()

def close(self):
self.cursor.close()
self.conn.close()