Python implements a simple MySQL class

Source: Internet
Author: User
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.

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.