This example describes Python's implementation of a simple MySQL class. Share to everyone for your reference.
The implementation methods are as follows:
Copy Code code as follows:
#!/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]
I hope this article will help you with your Python programming.