python mysql database operations
1, the installation pymysql library
Pymysql install third-party libraries in python, installed by pip install pymysql command.
2, python mysql database Procedure
- Establish a database connection, connect to the database connect
- Create a cursor cursor
- Executes the corresponding sql statement
- Query to get the data
3, get two way query data
- Method 1: Obtain a query data
= cur.fetchone data_one () # cursor name .fetchone ()
- Second way: Get all the query data
= cur.fetchall the Data () # cursor name .fetchall ()
4, python mysql database operator specific code
Import pymysql # . 1, is connected to the database CON = pymysql.connect (Host = ' IP ' , Port = 3306 , User = ' Test ' , password = ' Test ' , Database = ' Future ' , charset = ' UTF8 ' ) # 2 creating a cursor cursor CUR = con.cursor () # . 3, performing the sql statement corresponding to execute () sql = '* from Member SELECT ' # query to the data quantity RES = cur.execute (SQL) Print (RES) # . 4, the query to obtain data # Method a: obtaining a query data data_one = cur.fetchone () Print (data_one ) # method two: Get all inquiries data data = cur.fetchall () Print (data)
5, pay attention
pymysql operate the database, transaction enabled by default, use con.commit () to commit the transaction, did not submit, then, the operation does not take effect.
6, a package own class mysql
purpose:
- Easy to read data
- The database is configured to extract the configuration file for easy management of test environment
import pymysql from common.config import conf class ReadMySQLData(object): def __init__(self): # 连接到数据库 self.con = pymysql.connect(host=conf.get('mysql','host'), port=conf.getint('mysql','port'), user=conf.get('mysql','user'), passwordconf.get = ( ' MySQL ' , ' password ' ), Database = conf.get ( ' MySQL ' , ' Database ' ), charset = ' utf8 ' ) # create a cursor self.cur = self.con.cursor () DEF find_one (Self, SQL): '' ' to locate and return the first data is found, the data is returned tuple type : SQL param: : return: ' '' self.cur.execute (SQL) self.con.commit() returnself.cur.fetchone () DEF find_all (Self, SQL): '' ' to locate and return all the data found, the data is returned tuple type : SQL param: : return: ' '' self.cur.execute (SQL ) self.con.commit () return self.cur.fetchall () DEF Close (Self): '' ' close the cursor, disconnect from the database : return: ' '' self.cur.close () self.con.close ()