Python's example of MySQL database operations

Source: Internet
Author: User
This article mainly introduced the Python3 operation MySQL database method, has the certain reference value, the interested small partner may refer to

Hardware and Software Environment

OS X EI Capitan
Python 3.5.1
MySQL 5.6

Objective

The use of databases is often involved in development, and Python has several workarounds for databases. This paper introduces the use of Pymysql module in the example of MySQL in Python3.

Prepare the database

Create a MySQL database, called TestDB, create a table called TestTable, it has 3 fields, respectively, is the ID, the data type is int (11), set the primary key, non-empty, UNSIGNED, AUTO Increment,name, Data type is varchar (45), set to non-null, unique, sex, data type is varchar (45), set to non-null

Python3 Source


#-*-Coding:utf-8-*-__author__ = ' djstava@gmail.com ' Import loggingimport pymysqlclass Mysqlcommand (object): Def __init __ (self,host,port,user,passwd,db,table): Self.host = host Self.port = Port Self.user = User Self.password = PA SSWD self.db = db self.table = Table def connectmysql (self): Try:self.conn = Pymysql.connect (host=self.hos t,port=self.port,user=self.user,passwd=self.password,db=self.db,charset= ' UTF8 ') self.cursor = Self.conn.cursor () E  Xcept:print (' Connect MySQL error. ') def querymysql (self): sql = "SELECT * from" + self.table try:self.cursor.execute (sql) row = Self.cursor.  Fetchone () print (row) except:print (sql + ' execute failed. ') def insertmysql (self,id,name,sex): sql = "INSERT into" + self.table + "VALUES" ("+ ID +", "+" "+" + "+" "'", "+")  + sex + "')" Try:self.cursor.execute (SQL) Except:print ("Insert failed.") def updatemysqlsn (self,name,sex): sql = "UPDATE" + SELf.table + "SET sex=" + Sex + "'" + "WHERE name= '" + name + "'" Print ("Update sn:" + sql) TRY:SELF.CURSOR.E    Xecute (SQL) Self.conn.commit () except:self.conn.rollback () def closemysql (self): Self.cursor.close () Self.conn.close ()

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.