pymysql
I. Summary
PyMySQL for a database connection MySQL server version in Python3.x,
Two, PyMySQL installation
pip install pymysql
Third, operational procedures
- Create a connection
- Gets cursor
- CRUD operations performed
- Data processing
- Close cursor
- Close connection
Fourth, the core classes Introduction
1. Create a connection
-
Explanation
-
Syntax
conn = pymysql.connect(host=None, user=None, password="", database=None, port=0, db=None,charset='')
-
Common Parameter Description
parameter name Types of Explanation host String MySQL server address port int MySQL port number user String username passwd String password db String Use of database charset String Connection character set -
return value
cursor
-
Sample Code
HOST = '127.0.0.1' PORT = 3306 USER = 'root' PASSWD = 'root' DB = 'python' CHARSET = 'utf8' connection = pymysql.connect(host=HOST, port=PORT, user=USER, passwd=PASSWD, db=DB, charset=CHARSET)
-
Other methods
method description begin() Open affairs commit() Commit the transaction cursor(cursor=None) Creating a cursor to execute the statement ping(reconnect=True) Check the connection is alive, will re-initiate the connection rollback() Roll back the transaction close() Close the connection select_db(db) Select Database show_warnings() View warning information -
detailed
- Host - the host database server resides.
- the User - login user name.
- password - the login user password.
- Database - a database connection.
- Port - open database ports. (Default: 3306)
- bind_address - when the client has multiple network interfaces, specify the interface connected to the host, the parameters may be the host name or IP address.
- unix_socket - using unix socket instead of tcp / ip.
- charset - the connection character set.
- sql_mode - default SQL mode.
- read_default_file - Specifies my.cnf file path to read parameters from the portion [client].
- CONV - conversion dictionary to be used instead of the default value.
- use_unicode - whether default is a unicode string, for Py3k, this option defaults to true.
- of client_flag - sent to MySQL custom logo.
- cursorClass - custom class using the cursor.
- init_command - SQL statements to establish the initial connection to run.
- connect_timeout - to establish a connection timeout. (Default: 10 Min: 1 Max: 31536000)
- read_default_group - group read from the configuration file.
- the compress - not supported
- named_pipe - not supported
- autocommit - set auto commit mode means that the database is not set by default. (Default: False)
- local_infile - whether to enable the use of the command "LOAD LOCAL INFILE". (Default: False)
- the max_allowed_packet - packet sent to the server the maximum size (in bytes, the default values: 16MB), only values smaller than the default size (16KB) in the "LOAD LOCAL INFILE" for restricting packet.
- defer_connect - do not explicitly connect building, waiting to connect calls. (Default: False)
- db - alias database connection (compatible MySQLdb)
- passwd - password enter an alias (compatible MySQLdb)
- binary_prefix - Add _binary prefix in bytes and bytearray (default: False)
2, target acquisition cursor
-
Explanation
Cursor object to execute the query and get results
-
The core method
Method name Explanation execute() For performing a database query fetchone() Gets the next row in the result set fetchmany(size) Get the next result set (size) line fetchall() Acquire all remaining rows in the result set rowcount The number of rows returned last execute data / effects close() Close the cursor -
For chestnuts
1, execute the query function
with connection.cursor() as cursor: sql = 'select * from home_user' cursor.execute(sql) results = cursor.fetchall() connection.commit() for results in results: uid = results[0] name = results[1] password = results[2] print('==========用户信息===============') print('用户id: {id} \n用户名: {name}\n密码: {pwd}'.format(id=uid, name=name, pwd=password))
-
detailed
method description close() Close the cursor. execute(query, args=None) Execute a single statement, statement of incoming need to do is string type; at the same time can pass parameters to the query, the parameter can be a tuple, list or dict. After execution, execution will return the number of rows impact statement, if any. executemany(query, args) Execute multiple INSERT statements, passing sentence to be executed; at the same time can pass parameters to the query, the argument is a sequence of mappings. After execution, execution will return the number of rows impact statement, if any. fetchone() Get the next row of data. fetchall() Get all data. fetchmany(size=None) Get a few lines of data. read_next() Get the next row of data. callproc() Used to call a stored procedure. mogrify () Parameterized queries to prevent SQL injection. scroll(num,mode) Move the cursor position.
Fifth, the basic operation
Query data
-
Paging query operation
def find_by_page(page, size): with pymysql.connect(host=HOST, port=PORT, user=USER, passwd=PASSWORD, charset=CHARSET, db=DB_NAME) as cursor: sql = "SELECT * FROM t_addr LIMIT{},{}".format((page - 1) * size, size) cursor.execute(sql) users = cursor.fetchall()
Transactional operations
-
Sample Code
conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='root', database='python', charset='utf8' ) cursor = conn.cursor() # 插入sql; sql_insert = "insert into t_user (userid,username) values (10,'user10')" # 更新sql; sql_update = "update t_user set username = 'name91' where userid=9" # 删除sql; sql_delete = "delete from t_user where userid < 3" # 把一个事务放到一个try块里,如果出现异常就回滚; try: # 开启事务; conn.begin() cursor.execute(sql_insert) print(cursor.rowcount) cursor.execute(sql_update) print(cursor.rowcount) cursor.execute(sql_delete) print(cursor.rowcount) # 提交事务; conn.commit() except Exception as e: # 若有异常就回滚; conn.rollback() cursor.close() conn.close()
Bulk Insert
-
Sample Code
# 测试事务 批量添加 def test_batch_insert(): conn = pymysql.connect(host=HOST, port=PORT, user=USER, passwd=PASSWORD, charset=CHARSET, db=DB_NAME) cursor = conn.cursor() try: sql = 'INSERT INTO t_addr(PROVICE, CITY, COUNTY, DEATIL, USERID) VALUES (%s,%s,%s,%s,%s)' li = [] for i in range(50): li.append(('湖北省', '武汉市', '高新区' + str(i), '智慧园', 6)) # 开启事物 conn.begin() cursor.executemany(sql, li) # 提交 conn.commit() except Exception as e: conn.rollback() print(e) # 报错事务回滚 finally: # 关闭连接 cursor.close() conn.close()