pymysql the database "cursor" and "connected cell" Analysis

1 Cursor

Cursor (Cursor) is a method for processing data, in order to see or deal with the result set of data, providing the ability to focus the cursor one row or multiple rows in the result forward or backward browsing data. Can be used as a pointer to the cursor, which can specify any position in the result, and then allow the user to specify the location of data processing
is that acquired operation data and results of the database to be operated by a cursor colloquially.
Database operations for step using the cursor as follows:

  1. cursor (), to create a cursor object
Cus = connect_mysql().cursour()
  1. execute (sql), method of execution of the statement. When we define a sql statement when you can use this method to execute the statement.
sql = select * from table1  
cus.execute(sql) 
  1. commit (), submits a command to commit the changes to the database
cus.commit()
  1. fetchall (), take all the results, it is to get the result obtained after executing sql statement. Cursor commonly used method
data=cus.fetchall()
  1. close (): Closes this cursor objects
cus.close()

Other cursor operation:
7. The fetchmany ([size = cursor.arraysize]): get the next result set lines
8. executemany (sql, args): executing a plurality of database queries or commands, try not to use executemany, continuously loop through the program excute function call

2 database connection pool

When pymysql python can be used to operate the database, but each time a database operation, we must re-establish the connection to the database, and the number of visits will greatly consume resources when a certain number. Therefore, the actual use, typically using a connection pool of database technology to access the database to achieve the purpose of resource reuse. Database connection pool is actually a database and establish a persistent TCP connection, so as to achieve resource database connection multiplexing.

Example:

def connect_myssql():
	conn = spool.connection()  #以后每次需要数据库连接就是用connection()函数获取连接
	cur = conn.cursor()
	SQL = "select * from tmp;"
	r = cur.execute(SQL)
	r = cur.fetchall()
	print(r)
	cur.close()
	conn.close()
Published 59 original articles · won praise 2 · Views 4690

Guess you like

Origin blog.csdn.net/lch551218/article/details/104288889