The operating python mysql

Reference article

import pymysql
import pandas
from IPython.core.display import display

db = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='root',
    db='test',
    charset='utf8'
)

cursor = db.cursor()
sql = " SELECT * from User " 
Result = the cursor.execute (SQL)
 # Result is the total number of receiving an int 
Print (Result) 

Data = cursor.fetchone ()
 # Print (Data) 

# FET series method ** extracting a result, instead of copying 
the resultSet = cursor.fetchall () 

Print (the resultSet) 

for I in the resultSet:
     Print (I) 

Print (len (the resultSet)) 

Print (the resultSet [0]) 

resultSet2 = cursor.fetchall () 

Print (resultSet2 ) 

for i inRange (len (the resultSet)):
     Print (I)
     Print (the resultSet [I]) 

the cursor.execute (SQL) 
the resultSet = cursor.fetchall () 

for A, B, C in the resultSet:
     Print ( " my name is {} , {} is a number, this is my password {} " .format (B, a, C)) 

# tabular display 
DF1 = pandas.read_sql (SQL, DB) 
the display (DF1) 

SQLInsert = ' INSERT INTO User (the uname , pwd) values ( "cow devil", "123123") ' 

the try : 
    the cursor.execute (SQLInsert) 
    the db.commit () 
the except :
     Print ("insert failed")
    db.rollback()
sqlinsert2 = 'insert into user (uname,pwd)values (%s,%s)'
insertdata = [("孙悟空","123456"),("唐僧","123123")]
try:
    cursor.executemany(sqlinsert2,insertdata)
    db.commit()
except:
    print("insertFailed")
    db.rollback()

sqlupdate = 'update user set pwd=%s where name=%s'
try:
    cursor.execute(sqlupdate,[90000,"玉皇大帝"])
    db.commit()
except:
    print("update failed")
    db.rollback()

db.close();

to sum up:

  • First: display () function from ipython, note guide packet
  • Second: Result = the cursor.execute (SQL)
    •   The results for the query result value of the number of
  • Third: the resultSet =cursor.fetchall ()
    •   Extraction results
  • Fourth: (% S,% S) to the data for matching, s represents a string
  • Fifth: for the statement to the three uses
    •   Direct use in keywords, matching a result (or sub-element)
    •         range (int a) the iterative range of 0 ~ a
    •        A, B, C in the resultSet A, B, C in sequence matching
  • Sixth: pymysql default transaction is open, manual submission

Guess you like

Origin www.cnblogs.com/lightandtruth/p/12523601.html