Python-mysql operation

Source: Internet
Author: User

Python connects the database to MySQL and operates the database:

1) First need to introduce module Pymysql, through the method of Pymysql connect to get the database connection, the code is as follows:

# db_name-database name, db_user-user name, db_pass-password, db_host-database ip;db_port-database port number; charset-encoding conn = Pymysql.connect (db=db _name, User=db_user, Passwd=db_pass, Host=db_host, port=db_port,charset='UTF8')

The above code note charset This parameter, do not set the parameter, the operation of the database may be reported as the following error:

' Ordinal not in range (256)

2) after connecting to the database, get the cursor:

# get cursor Cursors = Conn.cursor ()

3) You can then manipulate the database:

#1 QueriesSel_sql ="""SELECT * from Product_class"""#perform a query operationCursor.execute (sel_sql)#convert the returned results to a dictionary formatdata = [Dict ((cursor.description[i][0], value) forI, ValueinchEnumerate (Row)) forRowinchCursor.fetchall ()]#Close cursors and database linkscursor.close () conn.close ( )#2 insertingInsert_sql ="""INSERT into Product_class (name, is_enable) VALUES (%s,%s);"""#Execute SQL statementcursor.execute (SQL, VARs)#Commit a transactionConn.commit ()## failure can be rolled back by catching an exception#Conn.rollback ()#Close cursors and database linkscursor.close () conn.close ( )#3 Modifying UpdatesUpdate_sql ="""UPDATE product_class SET name=%s, is_enable=%s WHERE id=10000;"""## Similar to insert Operation

Python-mysql operation

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.