Python implements a simple MySQL class, and python implements mysql

Source: Internet
Author: User

Python implements a simple MySQL class, and python implements mysql

This example describes how to implement a simple MySQL class in Python. Share it with you for your reference.

The specific implementation method is as follows:

Copy codeThe 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.