MySQL database in Python

Source: Internet
Author: User

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:


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)
# 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)
Print "error:unable to FECTH data"

# Close the database connection
Db.close ()

MySQL database in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.