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