Python中pymysql的使用方法

本文涉及的产品
RDS AI 助手,专业版
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
简介: Python中pymysql的使用方法

本次测试创建的数据及表:

复制代码

创建数据库及表,然后插入数据

mysql> create database dbforpymysql;
mysql> create table userinfo(id int not null auto_increment primary key,username varchar(10),passwd varchar(10))engine=innodb default charset=utf8;
mysql> insert into userinfo(username,passwd) values('frank','123'),('rose','321'),('jeff',666);

查看表内容

mysql> select * from userinfo;
+----+----------+--------+
| id | username | passwd |
+----+----------+--------+
| 1 | frank | 123 |
| 2 | rose | 321 |
| 3 | jeff | 666 |
+----+----------+--------+
3 rows in set (0.00 sec)
复制代码
连接数据库:

复制代码
import pymysql

连接数据库

db = pymysql.connect("localhost","root","LBLB1212@@","dbforpymysql")

使用cursor()方法创建一个游标对象

cursor = db.cursor()

使用execute()方法执行SQL语句

cursor.execute("SELECT * FROM userinfo")

使用fetall()获取全部数据

data = cursor.fetchall()

打印获取到的数据

print(data)

关闭游标和数据库的连接

cursor.close()
db.close()

运行结果

((1, 'frank', '123'), (2, 'rose', '321'), (3, 'jeff', '666'))
复制代码
要完成一个MySQL数据的连接,在connect中可以接受以下参数:

复制代码
def init(self, host=None, user=None, password="",
database=None, port=0, unix_socket=None,
charset='', sql_mode=None,
read_default_file=None, conv=None, use_unicode=None,
client_flag=0, cursorclass=Cursor, init_command=None,
connect_timeout=10, ssl=None, read_default_group=None,
compress=None, named_pipe=None, no_delay=None,
autocommit=False, db=None, passwd=None, local_infile=False,
max_allowed_packet=1610241024, defer_connect=False,
auth_plugin_map={}, read_timeout=None, write_timeout=None,
bind_address=None):
参数解释:
host: Host where the database server is located #主机名或者主机地址
user: Username to log in as #用户名
password: Password to use. #密码
database: Database to use, None to not use a particular one. #指定的数据库

//代码效果参考:https://v.youku.com/v_show/id_XNjQwNjg0MjkzMg==.html
port: MySQL port to use, default is usually OK. (default: 3306) #端口,默认是3306
bind_address: When the client has multiple network interfaces, specify
the interface from which to connect to the host. Argument can be
a hostname or an IP address. #当客户端有多个网络接口的时候,指点连接到数据库的接口,可以是一个主机名或者ip地址
unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
charset: Charset you want to use. #指定字符编码
sql_mode: Default SQL_MODE to use.
read_default_file:
Specifies my.cnf file to read these parameters from under the [client] section.
conv:
Conversion dictionary to use instead of the default one.
This is used to provide custom marshalling and unmarshaling of types.
See converters.
use_unicode:
Whether or not to default to unicode strings.
This option defaults to true for Py3k.
client_flag: Custom flags to send to MySQL. Find potential values in constants.CLIENT.
cursorclass: Custom cursor class to use.
init_command: Initial SQL statement to run when connection is established.
connect_timeout: Timeout before throwing an exception when connecting.
(default: 10, min: 1, max: 31536000)
ssl:
A dict of arguments similar to mysql_ssl_set()'s parameters.
For now the capath and cipher arguments are not supported.
read_default_group: Group to read from in the configuration file.
compress; Not supported
named_pipe: Not supported
autocommit: Autocommit mode. None means use server default. (default: False)
local_infile: Boolean to enable the use of LOAD DATA LOCAL command. (default: False)
max_allowed_packet: Max size of packet sent to server in bytes. (default: 16MB)
Only used to limit size of "LOAD LOCAL INFILE" data packet smaller than default (16KB).
defer_connect: Don't explicitly connect on contruction - wait for connect call.
(default: False)
auth_plugin_map: A 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)
db: Alias for database. (for compatibility to MySQLdb)
passwd: Alias for password. (for compatibility to MySQLdb)
复制代码
cursor其实是调用了cursors模块下的Cursor的类,这个模块主要的作用就是用来和数据库交互的,当你实例化了一个对象的时候,你就可以调用对象下面的各种绑定方法:

复制代码
class Cursor(object):
"""
This is the object you use to interact with the database.
"""
def close(self):
"""
Closing a cursor just exhausts all remaining data.
"""
def setinputsizes(self, *args):
"""Does nothing, required by DB API."""

def setoutputsizes(self, *args):
    """Does nothing, required by DB API."""        
def execute(self, query, args=None):
    """Execute a query

    :param str query: Query to execute.

    :param args: parameters used with query. (optional)
    :type args: tuple, list or dict

    :return: Number of affected rows
    :rtype: int

    If args is a list or tuple, %s can be used as a placeholder in the query.

//代码效果参考:https://v.youku.com/v_show/id_XNjQwNjg0MTMwMA==.html
If args is a dict, %(name)s can be used as a placeholder in the query.
"""
def executemany(self, query, args):

    # type: (str, list) -> int
    """Run several data against one query

    :param query: query to execute on server
    :param args:  Sequence of sequences or mappings.  It is used as parameter.
    :return: Number of rows affected, if any.

    This method improves performance on multiple-row INSERT and
    REPLACE. Otherwise it is equivalent to looping over args with
    execute().
    """
def fetchone(self):
    """Fetch the next row"""
def fetchmany(self, size=None):
    """Fetch several rows"""
def fetchall(self):
    """Fetch all the rows"""
......

复制代码

数据库操作
一、数据库增删改操作
commit()方法:在数据库里增、删、改的时候,必须要进行提交,否则插入的数据不生效。

复制代码
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES('jack','123')"
cursor.execute(sql)
db.commit() #提交数据
cursor.close()
db.close()
或者在execute提供插入的数据
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(
config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"
cursor.execute(sql,("bob","123"))
db.commit() #提交数据
cursor.close()
db.close()
复制代码

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。   相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情: https://www.aliyun.com/product/rds/mysql 
相关文章
|
JSON JavaScript 前端开发
Python中使用JsonPath:概念、使用方法与案例
Python中使用JsonPath:概念、使用方法与案例
832 0
|
5月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
661 1
|
关系型数据库 MySQL Python
pymysql模块,python与MySQL之间的交互
pymysql模块,python与MySQL之间的交互
|
SQL 关系型数据库 MySQL
Python系列:教你使用PyMySQL操作MySQL数据库
Python系列:教你使用PyMySQL操作MySQL数据库
999 8
|
SQL 关系型数据库 MySQL
Python中Pymysql库的常见用法和代码示例
`pymysql` 是一个用于连接 MySQL 数据库的 Python 库,支持 SQL 查询的执行和结果处理。通过 `pip install pymysql` 安装后,可使用 `connect()` 方法建立连接,`cursor()` 创建游标执行查询,包括数据的增删改查,并通过 `commit()` 和 `rollback()` 管理事务,最后需关闭游标和连接以释放资源。
668 0
|
开发者 Python
Python函数与模块使用方法
【7月更文挑战第24天】Python 是一种功能强大的编程语言,拥有丰富的函数和模块,使得开发者能够轻松地构建复杂的应用程序。本文将介绍 Python 中函数和模块的基本使用方法,并提供一些代码实例。
|
关系型数据库 MySQL 数据管理
pymysql:Python操作MySQL数据库的又一利器
pymysql:Python操作MySQL数据库的又一利器
202 0
|
SQL 关系型数据库 MySQL
Python操作pymysql数据库的流程与技巧
在现代软件开发中,Python作为一门高效且易于学习的编程语言,广泛应用于各种场景,其中包括数据库操作。**PyMySQL** 是一个流行的Python数据库接口,用于连接和操作MySQL数据库。它提供了一种简便的方法来执行SQL语句、处理数据和管理数据库事务。以下是使用PyMySQL操作MySQL数据库的流程与技巧,旨在为开发者提供一个清晰、实用的指南。
240 0
|
定位技术 Python
Python的try、except异常处理模块使用方法
所以,我们就解决了由于可能具有的arcpy.ExecuteError异常而导致的程序中断问题;大家在实际使用时,按照自己程序中可能出现的报错类,对本文出现的arcpy.ExecuteError异常类加以修改即可。
3个常用的Python性能分析工具及其使用方法
以下是几个常用的性能分析工具及其使用方法和常用命令:

推荐镜像

更多