Home > Database > Mysql Tutorial > body text

Share a MySQL client operation library implemented in pure Python

php是最好的语言
Release: 2018-07-25 16:33:58
Original
2222 people have browsed it

PyMySQL is a MySQL client operation library implemented in pure Python, supporting transactions, stored procedures, batch execution, etc. PyMySQL follows the Python Database API v2.0 specification and includes the pure-Python MySQL client library.

Installation

pip install PyMySQL
Copy after login

Create database connection

import pymysql

connection = pymysql.connect(host='localhost',
                             port=3306,
                             user='root',
                             password='root',
                             db='demo',
                             charset='utf8')
Copy after login

Parameter list:

ParameterDescription
hostDatabase server address, default localhost
user Username, defaults to the user running the current program
password Login password, defaults to an empty string
databaseDefault operation database
portDatabase port, the default is 3306
bind_address When the client has multiple network interfaces, specify the interface to connect to the host. Parameters can be hostnames or IP addresses.
unix_socketunix socket address, different from host connection
read_timeoutRead Data timeout, in seconds, unlimited by default
write_timeout Write data timeout, in seconds, unlimited by default
charsetDatabase encoding
sql_modeSpecify the default SQL_MODE
read_default_fileSpecifies my.cnf file to read these parameters from under the [client] section.
convConversion dictionary to use instead of the default one. This is used to provide custom marshalling and unmarshaling of types.
use_unicodeWhether or not to default to unicode strings. This option defaults to true for Py3k.
client_flagCustom flags to send to MySQL. Find potential values ​​in constants.CLIENT.
cursorclassSet the default cursor type
init_commandInitialization SQL statement executed after the connection is established
connect_timeoutConnection timeout, default 10, minimum 1, maximum 31536000
sslA dict of arguments similar to mysql_ssl_set()'s parameters. For now the capath and cipher arguments are not supported.
read_default_groupGroup to read from in the configuration file.
compress Not supported
named_pipeNot supported
autocommitIs it automatic Submit, the default is not to submit automatically, the parameter value is None, which means it is subject to the server
local_infileBoolean to enable the use of LOAD DATA LOCAL command. (default: False )
max_allowed_packetThe maximum amount of data sent to the server, the default is 16MB
defer_connect Whether to connect lazily, the default is to connect immediately
auth_plugin_mapA dict of plugin names to a class that processes that plugin. The class will take the Connection object as the argument to the constructor. The class needs an authenticate method taking an authentication packet as an argument. For the dialog plugin, a prompt(echo, prompt) method can be used (if no authenticate method) for returning a string from the user. (experimental )
server_public_keySHA256 authenticaiton plugin public key value. (default: None)
dbAlias ​​of parameter database
passwdAlias ​​of parameter password
binary_prefixAdd _binary prefix on bytes and bytearray. (default: False)

执行 SQL

  • cursor.execute(sql, args) 执行单条 SQL

    # 获取游标
    cursor = connection.cursor()
    
    # 创建数据表
    effect_row = cursor.execute('''
    CREATE TABLE `users` (
      `name` varchar(32) NOT NULL,
      `age` int(10) unsigned NOT NULL DEFAULT '0',
      PRIMARY KEY (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    ''')
    
    # 插入数据(元组或列表)
    effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s)', ('mary', 18))
    
    # 插入数据(字典)
    info = {'name': 'fake', 'age': 15}
    effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%(name)s, %(age)s)', info)
    
    connection.commit()
    Copy after login
  • executemany(sql, args) 批量执行 SQL

    # 获取游标
    cursor = connection.cursor()
    
    # 批量插入
    effect_row = cursor.executemany(
        'INSERT INTO `users` (`name`, `age`) VALUES (%s, %s) ON DUPLICATE KEY UPDATE age=VALUES(age)', [
            ('hello', 13),
            ('fake', 28),
        ])
    
    connection.commit()
    Copy after login

注意:INSERT、UPDATE、DELETE 等修改数据的语句需手动执行connection.commit()完成对数据修改的提交。

获取自增 ID

cursor.lastrowid
Copy after login

查询数据

# 执行查询 SQL
cursor.execute('SELECT * FROM `users`')

# 获取单条数据
cursor.fetchone()

# 获取前N条数据
cursor.fetchmany(3)

# 获取所有数据
cursor.fetchall()
Copy after login

游标控制

所有的数据查询操作均基于游标,我们可以通过cursor.scroll(num, mode)控制游标的位置。

cursor.scroll(1, mode='relative') # 相对当前位置移动
cursor.scroll(2, mode='absolute') # 相对绝对位置移动
Copy after login

设置游标类型

查询时,默认返回的数据类型为元组,可以自定义设置返回类型。支持5种游标类型:

  • Cursor: 默认,元组类型

  • DictCursor: 字典类型

  • DictCursorMixin: 支持自定义的游标类型,需先自定义才可使用

  • SSCursor: 无缓冲元组类型

  • SSDictCursor: 无缓冲字典类型

无缓冲游标类型,适用于数据量很大,一次性返回太慢,或者服务端带宽较小时。源码注释:

Unbuffered Cursor, mainly useful for queries that return a lot of data, or for connections to remote servers over a slow network.

Instead of copying every row of data into a buffer, this will fetch rows as needed. The upside of this is the client uses much less memory, and rows are returned much faster when traveling over a slow network
or if the result set is very big.

There are limitations, though. The MySQL protocol doesn't support returning the total number of rows, so the only way to tell how many rows there are is to iterate over every row returned. Also, it currently isn't possible to scroll backwards, as only the current row is held in memory.

创建连接时,通过 cursorclass 参数指定类型:

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='root',
                             db='demo',
                             charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor)
Copy after login

也可以在创建游标时指定类型:

cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
Copy after login

事务处理

  • 开启事务

connection.begin()

  • 提交修改

connection.commit()

  • 回滚事务

connection.rollback()

防 SQL 注入

  • 转义特殊字符
    connection.escape_string(str)

  • 参数化语句
    支持传入参数进行自动转义、格式化 SQL 语句,以避免 SQL 注入等安全问题。

# 插入数据(元组或列表)
effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%s, %s)', ('mary', 18))

# 插入数据(字典)
info = {'name': 'fake', 'age': 15}
effect_row = cursor.execute('INSERT INTO `users` (`name`, `age`) VALUES (%(name)s, %(age)s)', info)

# 批量插入
effect_row = cursor.executemany(
    'INSERT INTO `users` (`name`, `age`) VALUES (%s, %s) ON DUPLICATE KEY UPDATE age=VALUES(age)', [
        ('hello', 13),
        ('fake', 28),
    ])
Copy after login

参考资料

  • Python中操作mysql的pymysql模块详解

  • Python之pymysql的使用

相关推荐:

python实现telnet客户端的方法

MemCached的PHP客户端操作类二

数据库mysql视频教程

The above is the detailed content of Share a MySQL client operation library implemented in pure Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template