pymysql of python operating mysql

1. Install pymysql

pip install pymysql

2. Operating the database

(1), connect and execute sql

import pymysql
  
#Create a connection, when connecting to a local server host='localhost' is better than host='127.0.0.1' 
con = pymysql.connect(host= ' 127.0.0.1 ' , port=3306, user= ' root ' , passwd= ' Password ' , db= ' library name ', charset='utf8' )
 #Create cursor 
cursor = db.cursor()
  
#Use the execute method to execute the SQL statement
effect_row = cursor.execute( "select * from table name " )
#Submit , otherwise the new or modified data cannot be saved  
con.commit()

#Close the cursor
cursor.close()

#Close the database connection
con.close()

Note: When there is Chinese, the connection needs to add charset='utf8', otherwise the Chinese will display garbled characters.

(2), get the newly created data auto-increment ID

import pymysql
  
con = pymysql.connect(host= ' localhost ' , port=3306, user= ' root ' , passwd= ' password ' , db= ' library name ' )
cursor = with.cursor()
cursor.executemany("insert into hosts(name,name_id)values(%s,%s)", [("abc",1),("def",2)])
con.commit ()
cursor.close()
con.close()
  
#Get the latest auto-increment ID 
new_id = cursor.lastrowid

(3), get query data

import pymysql
 
con = pymysql.connect(host= ' loacalhost ' , port=3306, user= ' root ' , passwd= ' password ' , db= ' library name ' )
cursor = with.cursor()
cursor.execute("select * from 表名")
 
#Get the first row of data for the remaining results 
row_1 = cursor.fetchone()

#Get the first n rows of data in the remaining results row_2 = cursor.fetchmany(n)
 
#Get all data of the remaining results row_3 = cursor.fetchall()
 
conn.commit()
cursor.close()
conn.close()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325077915&siteId=291194637