1. Standard process for working with MySQL
ImportPymysqlconn= Pymysql.connect (host ="127.0.0.1", port = 3306,user ="Root", passwd ="*******", db ="Homework", CharSet ="UTF8") Cursor=conn.cursor () R= Cursor.execute ("Show Tables") Conn.commit () Cursor.close () Conn.close ( )
The code above implements a standard process for working with MySQL under Pycharm. Among the key points are:
#. Create a connection
conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘t1‘)
#. Creating Cursors
cursor= conn.cursor()
#. EXECUTE statement
Cursor. Execute ("") where the quotation marks are in the MySQL statement
#. Submit
conn.commit()
#. Close Cursors and connections
Cursor.close () Conn.close ()
2. Get the self-increment ID
new_id = cursor.lastrowid
3. Querying Data
# 获取第一行数据
row_1 = cursor.fetchone()
# 获取前n行数据
# row_2 = cursor.fetchmany(3)
# 获取所有数据
# row_3 = cursor.fetchall()
This one has pointers to the movement of the Cursor.scroll (1,mode= ' relative ') relative to the movement of positive or negative corresponding to move up and down Cursor.scroll (1,mode= ' absolute ') to the absolute position.
Control the format of data fetching by setting parameters after the cursor bracket, such as: Dictionary cursor = conn.cursor (cursor=pymysql.cursors.dictcursor)
PY Operation MySQL