Use Python to operate MySQL Databases and pythonmysql Databases

Source: Internet
Author: User

Use Python to operate MySQL Databases and pythonmysql Databases

1. Install mysql-python

Run the following command:

Pip intall mysql-python

After installation:

Import MySQLdb

If no error occurs, the installation is successful.

2. Connect to MySQL

Db = MySQLdb. connect ("localhost", "root", "1", "fs ")

Specifically, localhost is the server name, root is the user name, 1 is the password, and fs is the database name, provided that the MySQL database has set the corresponding user name and password.

After the connection is successful

Cur = db. cursor ()

Obtain the cursor.

3. query data
Cur.exe cute ("select * from TableName where A = % s and B = % s order by C desc", (a, B) results = cur. fetchall () result = list (results)

Cur.exe cute () executes the query statement. cur. fetchal () gets the result set and converts the result set to a tuple Array Using list (). The rest is easy to process.

4. Write Data
Cur.exe cute ("insert into A values (% s, % s)", (x1, x2, x3, x4) db. commit ()

Regardless of the type of the written field in the table, % s is used. Otherwise, an error occurs. After writing, commit () is required ().

The other operations include the deleteand updateoperations, both of which are temporary. You can use cur.exe cute () to execute the SQL statement and use % s to substitute the parameter.

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: info-contact@alibabacloud.com 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.