The MySQL module in Python2 is Mysqldb,python2 and starts using Pymysql.
HTTPS://WWW.PYTHON.ORG/DEV/PEPS/PEP-0249/is the official document for the Python DB API.
Connection Object Conncet
Creates a constructor that connects to the database, returns a Connection object, and requires some database-related parameters (HOST,USER,PASSWD,DB).
Connection method
The connection object will return some methods
. Close ()
Close the connection immediately. From this point in time, the connection is unavailable, and if there is an operation on the connection, an error exception occurs. If no commit is directly close after modifying the data, the modification is not valid.
. Commit ()
Commits a pending state modification to the DB. If the DB supports the Auto-commit attribute, the commit is closed at first, but it can be opened through an interface.
. Rollback ()
This method will roll the DB back to the beginning of all pending operations.
. Cursor ()
Use this connection to return a new cursor object.
Cursors Object cursor
These objects are used to manage database write operations and return output. Cursors are connection-based, different cursors of the same connection, and operations are instantly visible to each other.
Cursor methods
. Execute (Operation)
Prepares and executes a database operation (query or command).
. Fetchone ()
The FETCH cursor returns the first row of the result. Output None if no data is returned.
. Fetchmany (N)
Fetch CURSOR returns the first n rows of the result
. Fetchall ()
The FETCH cursor returns all of the results. It can affect performance.
Exception module
Error
#coding: Utf-8import pymysql# Connection Database conn = Pymysql.connect ("192.168.146.73", "root", "123.com", "config") cursor = Conn.cursor () #获取自增值并赋值cursor. Execute ("select Max (AppID) + 1 from svrprocessconfig") new_id = Cursor.fetchone () #写入数据sql = ' INSERT into Svrprocessconfig VALUES (%d,290, ' thrdcnt=3; ', ' XX ', 1) '% (new_id) Try: cursor.execute (SQL) Conn.commit () except: conn.rollback () #关闭连接conn. Close ()
2-python3 Operation MYQL