How does Python query Mysql

The Python query Mysql uses the fetchone() method to obtain a single piece of data, and the fetchall() method to obtain multiple pieces of data.

  • fetchone(): This method fetches the next query result set. The result set is an object
  • fetchall(): Receive all returned result rows.
  • rowcount: This is a read-only property and returns the number of rows affected by executing the execute() method.

1: Use the fetchone() method to get the result set

import pymysql

#Open database connection 
db = pymysql.connect ( " localhost " , " root " , " 123456 " , " test " )

#Use the cursor() method to get the operation cursor 
cursor = db.cursor()

# SQL query statement 
sql = " SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d' " % (1000 )
 try :
     #Execute SQL statement 
    cursor.execute(sql)
     print (cursor.rownumber)
    result = cursor.fetchone()
    while result!=None:
        print(result, cursor.rownumber)
        result = cursor.fetchone()

    result = cursor.fetchone()
    print(result, cursor.rownumber)
    result = cursor.fetchone()
    print(result, cursor.rownumber)

except:
   print ("Error: unable to fetch data")

#Close the database connection 
db.close()

Output result:

0
('Mac', 'Mohan', 20, 'M', 2000.0) 1
('Marry', 'Mohan', 32, 'M', 3000.0) 2
('Bob', 'Mohan', 21, 'F', 4000.0) 3
None 3
None 3

Conclusion: After executing the cursor.execute(sql) statement, the cursor points to the position before the first record.

          After executing the cursor.fetchone() statement, the fetchone() method returns the next record pointed to by the cursor, and the cursor points to the next record of the current record.

    When the cursor has pointed to the last record, after executing the cursor.fetchone() statement again, the result returns None, and the cursor no longer moves forward.

 

2: fetchall(): Receive all returned result rows

import pymysql

#Open database connection 
db = pymysql.connect ( " localhost " , " root " , " 123456 " , " test " )

#Use the cursor() method to get the operation cursor 
cursor = db.cursor()

# SQL query statement 
sql = " SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d' " % (1000 )
 try :
     #Execute the SQL statement 
    cursor.execute(sql)
     #Get a list of all records 
    results = cursor.fetchall()
     for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        # 打印结果
        print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" %
              (fname, lname, age, sex, income))
except:
   print ("Error: unable to fetch data")

#Close the database connection 
db.close()

 

Guess you like

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