Python to implement a simple MySQL class _python

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.