您的位置:首页 > 编程语言 > Python开发

python操作数据库学习,自封装一个类来处理

2011-09-29 18:17 716 查看
自封装一个简单的类来测试一下,挺不错。。。

import MySQLdb

class WebSiteDB:

def __init__(self, dbname = 'website', hostname = 'localhost', username = 'root', password = 'test'):

self.dbname = dbname

self.hostname = hostname

self.username = username

self.password = password

self.conn = None

self.cursor = None

self.__connectMySql()

self.__createDB()

self.__selectDB()

def __connectMySql(self):

try:

self.conn = MySQLdb.connect(host = self.hostname, user = self.username, passwd = self.password)

self.cursor = self.conn.cursor()

except:

print 'fail to connect to MySQLdb '

def __createDB(self):

try:

sqlcmd = 'create database if not exists ' + self.dbname

self.cursor.execute(sqlcmd)

except:

print 'fail to create database ' + self.dbname

return None

def __selectDB(self):

try:

self.conn.select_db(self.dbname)

except:

print 'fail to select_db ', self.dbname

def createTable(self, tablename):

try:

if tablename is None:

return None

sqlcmd = 'create table if not exists ' + tablename + '(website varchar(50), url varchar(300))'

self.cursor.execute(sqlcmd)

except:

print 'fail to create table ' + tablename

return None

def fetchOne(self, tablename):

try:

self.cursor.execute('select * from ' + tablename)

result = self.cursor.fetchone()

return result

except:

print 'fail to fetchOne'

return None

def fetchMany(self, tablename, num):

try:

self.cursor.execute('select * from ' + tablename)

results = self.cursor.fetchmany(num)

return results

except:

print 'fail to fetchMany ', num

return None

def fetchAll(self, tablename):

try:

self.cursor.execute('select * from ' + tablename)

results = self.cursor.fetchall()

return results

except:

print 'fail to fetchAll'

return None

def insertOneRd(self, tablename, value):

try:

sqlcmd = 'insert into ' + tablename + ' values(%s, %s)'

self.cursor.execute(sqlcmd, value);

except:

print 'fail to insertOneRd'

return None

def insertManyRd(self, tablename, values):

try:

sqlcmd = 'insert into ' + tablename + ' values(%s, %s)'

self.cursor.executemany(sqlcmd, values)

except:

print 'fail to insetManyRd'

return None

def droptable(self, tablename):

while True:

self.cursor.execute('show tables like "%s%%"' % tablename)

tables = self.cursor.fetchall()

if len(tables) == 0:

break

for x in tables:

try:

self.cursor.execute('drop table %s' % x)

self.conn.commit()

except:

continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐