Python operation MySQL Database python3 operation MySQL data need to install a third-party module, Pymysql, using pip install Pymysql installation, in Python2 is the MySQLdb module, There are no MYSQLDB modules in Python3, so use Pymysql.
First, operating data
The operational database is divided into several steps
1. Connect the database account password IP port number database
2. Creating Cursors
3. Execute SQL
4. Get Results
5. Close the cursor
6. Link Close
1Sql_connect =Pymysql.connect (2host='118.24.3.40', user='Jxz', passwd='123456',3port=3306,db='Jxz', charset='UTF8'4 #Port must write int type5 #CharSet must write UTF8 here .6 )7cur = sql_connect.cursor ()#Creating Cursors8Cur.execute ('select * from Stu;')#Execute SQL9res = Cur.fetchall ()#get all returned resultsTen One #Cur.execute (' INSERT INTO Stu VALUE (6, "Ytt", "female"); A #Delete Update INSERT statement requires a commit - #Sql_connect.commit () - the Print(RES) -Cur.close ()#Close Cursors -Sql_connect.close ()#Close Link
Write a function to the operations database
1 defmy_db (host,user,passwd,db,sql,port=3306,charset='UTF8'):2 ImportPymysql3Coon = Pymysql.connect (user=User,4host=Host,5port=Port,6Passwd=passwd,7db=DB,8charset=CharSet9 )Tencur = coon.cursor ()#Creating Cursors OneCur.execute (SQL)#Execute SQL A ifSql.strip () [: 6].upper () = ='SELECT': -res =Cur.fetchall () - Print(RES) the Else: - Coon.commit () -res ='OK' - cur.close () + coon.close () - returnRes
python--Operating Database