Python实现一个简单的MySQL类
程序员文章站
2022-06-20 23:53:46
本文实例讲述了python实现一个简单的mysql类。分享给大家供大家参考。
具体实现方法如下:
复制代码 代码如下:#!/usr/bin/env python
#...
本文实例讲述了python实现一个简单的mysql类。分享给大家供大家参考。
具体实现方法如下:
复制代码 代码如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# created on 2011-2-19
# @author: xiaoxiao
import mysqldb
import sys
__all__ = ['mysql']
class mysql(object):
'''
mysql
'''
conn = ''
cursor = ''
def __init__(self,host='localhost',user='root',passwd='root',db='mysql',charset='utf8'):
"""mysql database initialization """
try:
self.conn = mysqldb.connect(host,user,passwd,db)
except mysqldb.error,e:
errormsg = 'cannot connect to server\nerror (%s): %s' %(e.args[0],e.args[1])
print errormsg
sys.exit()
self.cursor = self.conn.cursor()
def query(self,sql):
""" execute sql statement """
return self.cursor.execute(sql)
def show(self):
""" return the results after executing sql statement """
return self.cursor.fetchall()
def __del__(self):
""" terminate the connection """
self.conn.close()
self.cursor.close()
#test
if __name__ == '__main__':
mysql = mysql(host=localhost,passwd='test',db='mysql')
mysql.query('select * from users')
result = mysql.show()
print len(result)
print result[1]
# -*- coding:utf-8 -*-
# created on 2011-2-19
# @author: xiaoxiao
import mysqldb
import sys
__all__ = ['mysql']
class mysql(object):
'''
mysql
'''
conn = ''
cursor = ''
def __init__(self,host='localhost',user='root',passwd='root',db='mysql',charset='utf8'):
"""mysql database initialization """
try:
self.conn = mysqldb.connect(host,user,passwd,db)
except mysqldb.error,e:
errormsg = 'cannot connect to server\nerror (%s): %s' %(e.args[0],e.args[1])
print errormsg
sys.exit()
self.cursor = self.conn.cursor()
def query(self,sql):
""" execute sql statement """
return self.cursor.execute(sql)
def show(self):
""" return the results after executing sql statement """
return self.cursor.fetchall()
def __del__(self):
""" terminate the connection """
self.conn.close()
self.cursor.close()
#test
if __name__ == '__main__':
mysql = mysql(host=localhost,passwd='test',db='mysql')
mysql.query('select * from users')
result = mysql.show()
print len(result)
print result[1]
希望本文所述对大家的python程序设计有所帮助。
上一篇: ps简单制作漂亮的圣诞贺卡教程