Working with Pymysql MySQL database

Source: Internet
Author: User
Tags rollback

Tool Library Installation

Pip Install Pymysql

Connect to shut down the database and increase the deletion check operation

#Import Pymysql LibraryImportPymysql#Open a database connection#parameter 1: Host + port number where database server resides#parameter 2: User name of the login database#parameter 3: password to log in to the database#parameter 4: The database to connect to#parameter 5: Character encodingdb =Pymysql.connect ('localhost',    'Root',    '123456',    'School', CharSet='UTF8')#Insert and delete operation#First, get a cursor objectcursor =db.cursor ()#Execute SQL statement#Create a table#"' Three quotes to write across the line#if not EXISTS indicates that the table is created if it does not exist#sql_table = "' CREATE table IF not EXISTS course (#c_id INT PRIMARY KEY auto_increment,#C_name VARCHAR (character) set GBK default NULL,#c_weight INT#) " "#Cursor.execute (sql_table)#Inserting Data#sql_add = " '# #INSERT into Course (c_name,c_weight) VALUES (' English ', ' 8 ');#" "#Try:#Cursor.execute (Sql_add)#Db.commit ()#except: # rollback Required If an exception occurs#Db.rollback ()#Delete Data#Sql_del = "DELETE from course WHERE c_name = ' math ';#" "#Try:#Cursor.execute (Sql_del)#Db.commit ()#except: # rollback Required If an exception occurs#Db.rollback ()#Modifying Data#Sql_change = "UPDATE course SET c_weight = 4 WHERE c_name = ' math ';#" "#Try:#Cursor.execute (Sql_change)#Db.commit ()#except: # rollback Required If an exception occurs#Db.rollback ()## Querying Data#sql_select = " '#SELECT * FROM Course#" "#Try:#Cursor.execute (sql_select)## get all records#results = Cursor.fetchall () # return to the progenitor#Print (results)#For row in results:##print (Row)#c_id = row[0]#c_name = row[1]#c_weight = row[2]#print (' name =%s,weight =%d '% (c_name,c_weight))##Db.commit ()#except:# rollback Required If an exception occurs#Db.rollback ()#To close a database connectionDb.close ()

Working with Pymysql MySQL database

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: 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.