Conn.commit () operation required after inserting, updating, deleting execution Conn.execute ()
Cursor.fetchone (): will take only the top first result, return a single tuple such as (' id ', ' title '), and then use Cursor.fetchone () multiple times to get the next result until it is empty.
Cursor.fetchall (): Returns all results, returning two-dimensional tuples, such as (' id ', ' title '), (' id ', ' title '),
If the select itself takes only one piece of data:
Cursor.fetchone (): Returns only one result, returning a single tuple such as (' id ', ' title ').
Cursor.fetchall (): will also return all results, returning two-dimensional tuples, such as (' id ', ' title '),
user_id = "test123"
Password = "Password"
Con.execute (' INSERT into Login ' values ('%s ', '%s ') '% \
(user_id, password))
Database Query Operations:
Fetchone (): This method gets the next query result set. The result set is an object
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.
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")
# get an action cursor using the cursor () method
cursor = Db.cursor ()
# SQL Query Statement
sql = "SELECT * from EMPLOYEE \
WHERE INCOME > '%d ' "% (1000)
Try
# Execute 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 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 the database connection
Db.close ()
MySQL database in Python