Pymysql contains a pure python library of MySQL clients that are designed to replace MYSQLDB and work in Cpython,pypy and IronPython.
Pymysql official address:https://pypi.python.org/pypi/PyMySQL#documentation
Here is a simple example and description:
dbinfo={ 'Host':'host_ip', 'Port': 3306, 'User':'user_name', 'Password':'Password', 'DB':'db_name', 'CharSet':'UTF8',}
defquerymysql (SQL):
#将数据库的信息当成字段传给connect (), which facilitates separation of data and functions, and can also write parameters directly in Connect () Conn= Pymysql.connect (* *DbInfo)
#建立连接后创建游标 cur=Conn.cursor ()
#执行sql语句, the SELECT statement also needs a fetch to get the data, otherwise it returns the number of data Cur.execute (SQL) Res=Cur.fetchall () cur.close ()
#sql语句不是自动提交的, manual commit required to remain modified Conn.commit ()
#执行sql语句后关闭连接 conn.close ()returnRessql='SELECT * FROM table_name'result=querymysql (SQL)Print(Result)
Here is an example of an official document that has been detailed, and I would simply add:
Importpymysql.cursors#Connect to the databaseConnection = Pymysql.connect (host='localhost', the user='User', Password='passwd', DB='DB', CharSet='UTF8MB4', Cursorclass=pymysql.cursors.dictcursor)#Cursorclass Select the format, dictionary, or list of returned data. #Try statement prevents assert interruptsTry: #using the WITH statement avoids shutting down the connection operationWith Connection.cursor () as cursor:#Create a new recordsql ="INSERT into ' users ' (' email ', ' password ') VALUES (%s,%s)"cursor.execute (SQL, ('[email protected]','Very-secret')) #connection is isn't autocommit by default. So-must commit to save #your changes.Connection.commit () with Connection.cursor () as cursor:#Read a single recordsql ="SELECT ' id ', ' password ' from ' users ' WHERE ' email ' =%s"cursor.execute (SQL, ('[email protected]',)) Result=Cursor.fetchone ()Print(Result)finally: Connection.close ()
Python Pymysql Module Learning experience