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