Preface
We all know that using Python to achieve MySQL operation is a very simple thing, only need to be skilled in using the MySQLdb module can be used to achieve the MySQL delete and modify operations.
In order to better integrate MySQL operations, it is a good idea to combine the Python-class MySQL-like operations. Here I write a simple class that implements the operation and query of MySQL.
Operation
In this example, we are going to create a test table T1, field ID and timestamp, the time stamp of the main storage system in MySQL Iceny, and the operation of adding, deleting, changing, and checking the table:
Status of current MySQL:
MySQLdb is a third-party module for Python, which needs to be installed prior to use, and the PIP installation is recommended here:
Pip Install Mysql-python
To write MySQL class classes:
#!/usr/local/env python3.6 # -*- coding: utf-8 -*-import mysqldbclass Mysql (object): def __init__ (self,host,port,user,passwd,db,charset= ' UTF8 '): "" "Initialize MySQL Connection" "" try: self.conn = mysqldb.connect ( HOST,USER,PASSWD,DB) except mysqldb.error as e: errormsg = ' cannot Connect to server\nerror (%s):%s ' % (e.args[0],e.args[1]) print (errormsg) exit (2) self.cursor = Self.conn.cursor ()   &NBSp; def exec (self,sql): "" "Execute DML,DDL Statement" "" try: Self.cursor.execute (SQL) self.conn.commit () except: self.conn.rollback () def query (self,sql): "" Query Data "" " self.cursor.execute (SQL) return self.cursor.fetchall () def __del__ (self): "" " close MySQL connection " " self.conn.close () Self.cursor.close ()
to create a MySQL object:
Mysql_test = Mysql (' 192.168.232.128 ', ' 3306 ', ' root ', ' 123456 ', ' Iceny ')
To create a table T1:
Mysql_test.exec (' CREATE TABLE t1 (id int auto_increment primary key,timestamp timestamp) ')
Insert a piece of data toward T1:
Mysql_test.exec (' INSERT into T1 (id,timestamp) value (Null,current_timestamp) ')
Update the data timestamp with ID 1, and then perform the current system time instead:
Insert a second piece of data to query the table data:
Mysql_test.exec (' INSERT into T1 (id,timestamp) value (null,current_timestamp) ') result = Mysql_test.query (' SELECT * FROM T1 ') print (result)
You can see that the results of the query are stored in a meta Zuzhong.
Delete data in table ID = 1:
Mysql_test.exec (' delete from t1 where id = 1 ')
The above is the simple implementation of the simple class operation by Python, MySQL additions and deletions, which has been able to cope with a large number of MySQL operations in daily work.
Python writes MySQL class to implement MySQL operation