Using Pymysql:
Installing Pymysql
Pip Install Pymysql
Code:
#Coding=utf8ImportPymysql#Create a Connection objectconn = Pymysql.connect (host='127.0.0.1', user='Root', password="', db='School')#Creating CursorsCur =conn.cursor ()#querying the contents of a table in a databasedefget_table (): Cur.execute ('SELECT name, address from teacher') R=Cur.fetchall ()Print(R)#get_table ()#executes SQL, queries a single piece of data, and returns the number of affected rowsEffect_row = Cur.execute ("Update teacher set name= ' Alice ' where Id=1")#print (Effect_row)#get_table ()#Insert multiple bars and return the affected number of barsEffect_rows = Cur.executemany ("insert into teacher (name, address) values (%s,%s)", [('AAA','A1'), ('BBB','B1'), ('CCC','C1')])#print (effect_rows)#get_table ()#get the latest self-increment IDnew_id =Cur.lastrowid#print (new_id)#Querying DataGet_datas = Cur.execute ('SELECT * from teacher')#get a row#row_1 = Cur.fetchone ()#print (row_1)#get up to 2 rows#row_2 = Cur.fetchmany (2)#print (row_2)Row_3=Cur.fetchall ()Print(row_3)#to reset a cursor to a dictionary typeCur = conn.cursor (cursor =pymysql.cursors.DictCursor)#Submit, save new or modified dataConn.commit ()#Close Cursorscur.close ()#Close ConnectionConn.close ()
Python Connection Database