This article mainly introduces how to implement a simple MySQL class in Python, which can implement basic functions such as initializing connections, querying and deleting, and has some reference value, for more information about how to implement a simple MySQL class in Python, see the example in this article. Share it with you for your reference.
The specific implementation method is as follows:
The code is 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)
Counter T 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.exe cute (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 Python programming.