[Python learning] operating Mysql

1. Introduction:

  MySQL is a relational database. Other relational databases include Oracle, DB2, Sql Server, etc. Python operation of MySQL requires the use of pymsyql module, pip can be installed.

Second, the operation of MySQL steps

  1. Connect to the database (IP, port number, user name, password, database name)

  2. Create a cursor

  3. Execute SQL

  4. Get results

  5. Close the cursor

  6. Close the connection

Copy code
1 import pymysql 
 2 conn = pymysql.connect ( 
 3 host = '192.168.1.112', 
 4 user = 'test', 
 5 passwd = '111111', 
 6 port = 3306, # port must be int type 
 7 db = 'test' , 
 8 charset = 'utf8' # charset must write utf8, not utf-8 
 9) 
10 sqla = 'select * from stu limit 10;' 
11 sqlb = 'insert into stu (id, name, sex) VALUE (10000, "张", "女"); '12 cur = conn.cursor () # Create a cursor without specifying the cursor type and return a two-dimensional tuple 
13 cur = conn.cursor (cursor = pymysql.cursors.DictCursor) # Create a cursor and specify the cursor type to return a dictionary 
14 cur.execute (sqla) # execute sqla 
15 cur.execute (sqlb) # execute sqlb  
16 conn.commit () # execute insert, delete, update statements must commit
17 res = cur.fetchall () # execute all the returned results, fetchall returns a two-dimensional array
18 res = cur.fetchone () # execute all returned results, fetchone returns the first line 
19 res = cur.fetchmany (2) # execute all returned results, fetchmany passes in a number and returns how many data 
20 res = cur.description # returns the information of each field in the table, description returns a two-dimensional array 
21 print (res) 
22 cur.close () # close the cursor 
23 conn.close () # close the connection
Copy code

 Cursor type:

  Without specifying the cursor type, ie: cur = conn.cursor (), the returned result is: ((5, 'Ben', male '), (6,' Lily ', female')), which is a two-dimensional Tuple

  Specify the curson type, that is: cur = conn.cursor (cursor = pymysql.cursors.DictCursor), the returned result is:

  [{'id': 5, 'name': 'Ben', 'sex': '男'}, {'id': 6, 'name': 'Lily', 'sex': '女'}]

The difference between fetchall () and fetchone ():

  fetchall (): Get all the results of this SQL execution, it puts each row of data in the database table into a tuple or dictionary

  fetchone (): Get a result of this SQL execution, it returns only a piece of data

  If the result of the SQL statement execution is multiple data, then use fetchall (), if you can be sure that there is only one result of the SQL execution, then use fetchone ()

Third, encapsulate the function of operating the MySQL database

Copy code
1 def my_db (sql, port = 3306, charset = 'utf8'): 
 2 import pymysql 
 3 host, user, passwd, db = '192.168.1.112', 'test', '111111', 'test' # define variable 
 4 conn = pymysql.connect (host = host, 
 5 user = user, 
 6 passwd = passwd, 
 7 port = port, 
 8 db = db, 
 9 charset = charset) 
10 cur = conn.cursor (cursor = pymysql.cursors.DictCursor) # Create a cursor and specify the cursor type to return a dictionary 
11 cur.execute (sql) # Execute statement 
12 if sql.strip (). Split () [0] .upper () == 'SELECT': # Determine whether the SQL statement Start with select 
13 res = cur.fetchall () 
14 else:
15         conn.commit()
16 res = 'OK' 
17 cur.close () # close the cursor 
18 conn.close () # close the connection 
19 return res
Copy code

 Fourth, practice

  Pass in a table name, export all data and write to excel file

Copy code
1 def export_excel (table_name): 
 2 import pymysql, xlwt 
 3 conn = pymysql.connect ( 
 4 host = '118.24.3.40', 
 5 user = 'jxz', 
 6 passwd = '123456', 
 7 port = 3306, 
 8 db = 'jxz', 
 9 charset = 'utf8') 
10 sql = 'select * from% s;'% table_name 
11 cur = conn.cursor () # Create a cursor without specifying the cursor type and return a two-dimensional tuple 
12 cur. execute (sql) # execute sql 
13 all_data = cur.fetchall () # get all the data in the table 
14 fileds = [filed [0] for filed in cur.description] # get all the fields of the table into a list 
15 book = xlwt.Workbook () # Create a new excel 
16 sheet = book.add_sheet ('sheet1') # Add sheet page
17 for col, filed in enumerate (fileds):   
18 sheet.write (0, col, filed) # Write the table header to the first row in the excel file 
19 row = 1 # Define the number of rows 
20 for data in all_data: # Control line 
21 for col, filed in enumerate (data): # Control column 
22 sheet.write (row, col, filed) 
23 row = row + 1 # Each time a row is written, add 1 
24 book.save ('% s.xls'% table_name)
Copy code

Guess you like

Origin www.cnblogs.com/gtea/p/12715597.html