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 ()