In this article, let's take a look at
Python databaseof knowledge, some friends may have just come into contact with the programming language of Python, not particularly in this regard, in the next article will bring you to learn about
python Query DatabaseKnowledge about the data in the.
Query operations for databases
Python queries MySQL uses the Fetchone () method to get a single piece of data, using the Fetchall () method to get multiple data.
1.fetchone (): This method gets the next query result set. The result set is an object
2.fetchall (): Receives all the returned result rows.
RowCount: This is a read-only property and returns the number of rows affected after the Execute () method is executed.
Example Demo
Query all data with the salary (payroll) field greater than 1000 in the employee table:
#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", " TESTDB ", charset= ' UTF8 ') # using the cursor () method to get the cursor cursor = db.cursor () # SQL query Statement sql =" SELECT * from EMPLOYEE \ WHERE INCO ME > '%d ' "%" try: # Execute SQL statement cursor.execute (SQL) # get all records list results = Cursor.fetchall () For row in results: fname = row[0] lname = row[1] Age = row[2] sex = row[3] income = row[4] # Print Results print "fname=%s,lname=%s,age=%d,sex=%s,income=%d"% \ (fname, lname, age, sex, income) except: print "error:unable to FECTH data" # Close database connection Db.close ()
The results of the above script execution are as follows:
Fname=mac, Lname=mohan, age=20, Sex=m, income=2000