python3.x: Connect to MySQL database using Pymysql
Python3.x is completely non-forward compatible, resulting in python2.x in the normal use of the library, to the Python3 can not be used;
For example MySQLdb, the current mysqldb does not support python3.x, python3.x connection to MySQL program has: Oursql, Pymysql, MYCONNPY, etc.
pymsql link MySQL database steps:1,pymysql Installation
Pymysql is a substitute for mysqldb in the PYTHON3 environment, enter the command line and use Pip to install Pymysql:
Pip Install Pymysql3
Installation Result:
2,pYmysql Connection Database (add, delete, change, check) example
#Importing a Pymysql packageImportPymysqlTry: #get a database connection, note if the UTF-8 type, you need to make a databaseConn=pymysql.connect (host='localhost', user='pythondb', passwd='pythondb', db='pythondb', port=3306,charset='UTF8') cur=conn.cursor ()#gets a cursor #Create user TableCursor.execute ("drop table if exists user") SQL="""CREATE TABLE IF not EXISTS ' user ' (' id ' int (one) not NULL auto_increment, ' name ' varchar (255) not NULL, ' age ' int (one) not NULL, PRIMARY KEY (' id ')) engine=innodb DEFAULT Charset=utf8 auto_in Crement=0"""cursor.execute (SQL)#User Insert DataSql="""INSERT into ' user ' (' name ', ' age ') VALUES (' test1 ', 1), (' Test2 ', 2), (' Test3 ', 3), (' Test4 ', 4), (' Test5 ', 5), (' Test6 ', 6);""" Try: #Execute SQL statementcursor.execute (SQL)#commit to database executionDb.commit ()except: #Rollback If an error occursDb.rollback ()#UpdateId=1SQL="Update user set age=100 where id= '%s '"%(ID)Try: Cursor.execute (SQL) Db.commit ()except: Db.rollback ()#Deleteid=2SQL="Delete from user where id= '%s '"%(ID)Try: Cursor.execute (SQL) Db.commit ()except: Db.rollback ()#EnquiryCur.execute ('SELECT * from user') Results=Cursor.fetchall () forRowinchResults:name=Row[0] age=row[1] #print (Type (row[1])) #打印变量类型 Print("name=%s,age=%s"%(age, name)) Cur.close ()#Close CursorsConn.close ()#Releasing database ResourcesexceptException:Print("failed")
python3.x: Connect to MySQL database using Pymysql