Python3连接MySQL

本文介绍Python3连接MySQL的第三方库--PyMySQL的基本使用。

PyMySQL介绍

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

Django中也可以使用PyMySQL连接MySQL数据库。

PyMySQL安装

#终端中安装pymysql
pip install pymysql
python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作
折腾好半天的数据库连接,由于之前未安装 pip ,而且自己用的python 版本为3.6. 只能用 pymysql 来连接数据库,(如果有和我一样未安装 pip 的朋友请 点这里http://blog.csdn.net/qq_37176126/article/details/72824404  ),下边 简单介绍一下 连接的过程,以及简单的增删改查操作。 1.通过 pip 安装 pymysql 进入 cmd  输入  pip install pymysql   回车等待安装完成; Python连接MySQL数据库之pymysql模块使用 随笔 第1张 安装完成后出现如图相关信息,表示安装成功。

连接数据库

MySQL 连接

使用mysql二进制方式连接

您可以使用MySQL二进制方式进入到mysql命令提示符下来连接MySQL数据库。

实例

以下是从命令行中连接mysql服务器的简单实例:

#[root@host]# mysql -u root -p
#Enter password:******

 

在登录成功后会出现 mysql> 命令提示窗口,你可以在上面执行任何 SQL 语句。

以上命令执行后,登录成功输出结果如下:

#Welcome to the MySQL monitor.  Commands end with ; or \g.
#Your MySQL connection id is 2854760 to server version: 5.0.9

#Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

 

在以上实例中,我们使用了root用户登录到mysql服务器,当然你也可以使用其他mysql用户登录。

如果用户权限足够,任何用户都可以在mysql的命令提示窗口中进行SQL操作。

退出 mysql> 命令提示窗口可以使用 exit 命令,如下所示:

mysql> exit
Bye

 

创建数据库

 

#-- 创建一个名为day59的数据库
Python连接MySQL数据库之pymysql模块使用 随笔 第2张

cerate database day59;
# -- 使用day59数据库
 use day59;
#-- 创建一个userinfo表
 create table userinfo (id int auto_increment primary key,name varchar(10) not null, pwd varchar(18) not null );

#-- 查看表结构是否正确
desc userinfo;
Python连接MySQL数据库之pymysql模块使用 随笔 第3张
#-- 添加3条测试数据 insert into userinfo (name, pwd) values ("alex", "alex3714"),("xiaohei", "123456"),("yimi", "654321"); #-- 查看数据 select * from userinfo; #-- 根据特定的用户名和密码从数据库中检索 select * from userinfo where name="alex" and pwd="alex3714";
Python连接MySQL数据库之pymysql模块使用 随笔 第4张
 
Python连接MySQL数据库之pymysql模块使用 随笔 第5张      

 

注意事项

在进行本文以下内容之前需要注意:

  • 你有一个MySQL数据库,并且已经启动。
  • 你有可以连接该数据库的用户名和密码
  • 你有一个有权限操作的database

基本使用

Python连接MySQL数据库之pymysql模块使用 随笔 第6张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 定义要执行的SQL语句
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
"""
# 执行SQL语句
cursor.execute(sql)
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第7张 Python连接MySQL数据库之pymysql模块使用 随笔 第8张
#注意:harset="utf8",中间没有空格,因为mySql不支持

 

 

返回字典格式数据:

Python连接MySQL数据库之pymysql模块使用 随笔 第9张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句并且将结果作为字典返回的游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 定义要执行的SQL语句
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
"""
# 执行SQL语句
cursor.execute(sql)
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第10张

 

注意:

charset=“utf8”,编码不要写成"utf-8"

数据库版登录

Python连接MySQL数据库之pymysql模块使用 随笔 第11张

Python连接MySQL数据库之pymysql模块使用 随笔 第12张

  

 

增删改查操作

 

Python连接MySQL数据库之pymysql模块使用 随笔 第13张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
# 执行SQL语句
cursor.execute(sql, [username, age])
# 提交事务
conn.commit()
cursor.close()
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第14张 Python连接MySQL数据库之pymysql模块使用 随笔 第15张 Python连接MySQL数据库之pymysql模块使用 随笔 第16张

Python连接MySQL数据库之pymysql模块使用 随笔 第17张

mysql端:

Python连接MySQL数据库之pymysql模块使用 随笔 第18张

 

Python连接MySQL数据库之pymysql模块使用 随笔 第19张

  

插入数据失败回滚

Python连接MySQL数据库之pymysql模块使用 随笔 第20张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
    # 执行SQL语句
    cursor.execute(sql, [username, age])
    # 提交事务
    conn.commit()
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()
cursor.close()
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第21张 Python连接MySQL数据库之pymysql模块使用 随笔 第22张 Python连接MySQL数据库之pymysql模块使用 随笔 第23张 Python连接MySQL数据库之pymysql模块使用 随笔 第24张

 

获取插入数据的ID(关联操作时会用到)

Python连接MySQL数据库之pymysql模块使用 随笔 第25张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
    # 执行SQL语句
    cursor.execute(sql, [username, age])
    # 提交事务
    conn.commit()
    # 提交之后,获取刚插入的数据的ID
    last_id = cursor.lastrowid
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()
cursor.close()
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第26张

Python连接MySQL数据库之pymysql模块使用 随笔 第27张

Python连接MySQL数据库之pymysql模块使用 随笔 第28张 

Python连接MySQL数据库之pymysql模块使用 随笔 第29张

 

批量执行

Python连接MySQL数据库之pymysql模块使用 随笔 第30张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
data = [("Alex", 18), ("Egon", 20), ("Yuan", 21)]
try:
    # 批量执行多条插入SQL语句
    cursor.executemany(sql, data)
    # 提交事务
    conn.commit()

except Exception as e: # 有异常,回滚事务 conn.rollback() cursor.close() conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第31张 Python连接MySQL数据库之pymysql模块使用 随笔 第32张 Python连接MySQL数据库之pymysql模块使用 随笔 第33张 Python连接MySQL数据库之pymysql模块使用 随笔 第34张 Python连接MySQL数据库之pymysql模块使用 随笔 第35张

由于数据库的编码格式不一样所以出现乱码:

创建数据库的时候指定编码需要:

Python连接MySQL数据库之pymysql模块使用 随笔 第36张

创建列表的时候也要指定一下,避免乱码:

Python连接MySQL数据库之pymysql模块使用 随笔 第37张

 

Python连接MySQL数据库之pymysql模块使用 随笔 第38张

 

 

Python连接MySQL数据库之pymysql模块使用 随笔 第39张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "DELETE FROM USER1 WHERE id=%s;"
try:
    cursor.execute(sql, [4])
    # 提交事务
    conn.commit()
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()
cursor.close()
conn.close()

Python连接MySQL数据库之pymysql模块使用 随笔 第40张 Python连接MySQL数据库之pymysql模块使用 随笔 第41张

 

Python连接MySQL数据库之pymysql模块使用 随笔 第42张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 修改数据的SQL语句
sql = "UPDATE USER1 SET age=%s WHERE name=%s;"
username = "Alex"
age = 80
try:
    # 执行SQL语句
    cursor.execute(sql, [age, username])
    # 提交事务
    conn.commit()
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()
cursor.close()
conn.close()

Python连接MySQL数据库之pymysql模块使用 随笔 第43张 Python连接MySQL数据库之pymysql模块使用 随笔 第44张

 

Python连接MySQL数据库之pymysql模块使用 随笔 第45张
#查询操作

import pymysql  #导入 pymysql  
  
#打开数据库连接  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)  
  
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
  
#1.查询操作  
# 编写sql 查询语句  user 对应我的表名  
sql = "select * from user"  
try:  
    cur.execute(sql)    #执行sql语句  
  
    results = cur.fetchall()    #获取查询的所有记录  
    print("id","name","password")  
    #遍历结果  
    for row in results :  
        id = row[0]  
        name = row[1]  
        password = row[2]  
        print(id,name,password)  
except Exception as e:  
    raise e  
finally:  
    db.close()  #关闭连接  

 

Python连接MySQL数据库之pymysql模块使用 随笔 第46张

 

查询单条数据

Python连接MySQL数据库之pymysql模块使用 随笔 第47张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 查询数据的SQL语句
sql = "SELECT id,name,age from USER1 WHERE id=1;"
# 执行SQL语句
cursor.execute(sql)
# 获取单条查询数据
ret = cursor.fetchone()
cursor.close()
conn.close()
# 打印下查询结果
print(ret)

Python连接MySQL数据库之pymysql模块使用 随笔 第48张
  
Python连接MySQL数据库之pymysql模块使用 随笔 第49张   

 

 

查询多条数据

Python连接MySQL数据库之pymysql模块使用 随笔 第50张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 查询数据的SQL语句
sql = "SELECT id,name,age from USER1;"
# 执行SQL语句
cursor.execute(sql)
# 获取多条查询数据
ret = cursor.fetchall()
cursor.close()
conn.close()
# 打印下查询结果
print(ret)

Python连接MySQL数据库之pymysql模块使用 随笔 第51张

 

  
Python连接MySQL数据库之pymysql模块使用 随笔 第52张   

 

 进阶用法

Python连接MySQL数据库之pymysql模块使用 随笔 第53张
# 可以获取指定数量的数据
cursor.fetchmany(3)
# 光标按绝对位置移动1
cursor.scroll(1, mode="absolute")
# 光标按照相对位置(当前位置)移动1
cursor.scroll(1, mode="relative")
Python连接MySQL数据库之pymysql模块使用 随笔 第54张

 

,

Python3连接MySQL

本文介绍Python3连接MySQL的第三方库--PyMySQL的基本使用。

PyMySQL介绍

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

Django中也可以使用PyMySQL连接MySQL数据库。

PyMySQL安装

#终端中安装pymysql
pip install pymysql
python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作
折腾好半天的数据库连接,由于之前未安装 pip ,而且自己用的python 版本为3.6. 只能用 pymysql 来连接数据库,(如果有和我一样未安装 pip 的朋友请 点这里http://blog.csdn.net/qq_37176126/article/details/72824404  ),下边 简单介绍一下 连接的过程,以及简单的增删改查操作。 1.通过 pip 安装 pymysql 进入 cmd  输入  pip install pymysql   回车等待安装完成; Python连接MySQL数据库之pymysql模块使用 随笔 第55张 安装完成后出现如图相关信息,表示安装成功。

连接数据库

MySQL 连接

使用mysql二进制方式连接

您可以使用MySQL二进制方式进入到mysql命令提示符下来连接MySQL数据库。

实例

以下是从命令行中连接mysql服务器的简单实例:

#[root@host]# mysql -u root -p
#Enter password:******

 

在登录成功后会出现 mysql> 命令提示窗口,你可以在上面执行任何 SQL 语句。

以上命令执行后,登录成功输出结果如下:

#Welcome to the MySQL monitor.  Commands end with ; or \g.
#Your MySQL connection id is 2854760 to server version: 5.0.9

#Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

 

在以上实例中,我们使用了root用户登录到mysql服务器,当然你也可以使用其他mysql用户登录。

如果用户权限足够,任何用户都可以在mysql的命令提示窗口中进行SQL操作。

退出 mysql> 命令提示窗口可以使用 exit 命令,如下所示:

mysql> exit
Bye

 

创建数据库

 

#-- 创建一个名为day59的数据库
Python连接MySQL数据库之pymysql模块使用 随笔 第56张

cerate database day59;
# -- 使用day59数据库
 use day59;
#-- 创建一个userinfo表
 create table userinfo (id int auto_increment primary key,name varchar(10) not null, pwd varchar(18) not null );

#-- 查看表结构是否正确
desc userinfo;
Python连接MySQL数据库之pymysql模块使用 随笔 第57张
#-- 添加3条测试数据 insert into userinfo (name, pwd) values ("alex", "alex3714"),("xiaohei", "123456"),("yimi", "654321"); #-- 查看数据 select * from userinfo; #-- 根据特定的用户名和密码从数据库中检索 select * from userinfo where name="alex" and pwd="alex3714";
Python连接MySQL数据库之pymysql模块使用 随笔 第58张
 
Python连接MySQL数据库之pymysql模块使用 随笔 第59张      

 

注意事项

在进行本文以下内容之前需要注意:

  • 你有一个MySQL数据库,并且已经启动。
  • 你有可以连接该数据库的用户名和密码
  • 你有一个有权限操作的database

基本使用

Python连接MySQL数据库之pymysql模块使用 随笔 第60张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 定义要执行的SQL语句
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
"""
# 执行SQL语句
cursor.execute(sql)
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第61张 Python连接MySQL数据库之pymysql模块使用 随笔 第62张
#注意:harset="utf8",中间没有空格,因为mySql不支持

 

 

返回字典格式数据:

Python连接MySQL数据库之pymysql模块使用 随笔 第63张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句并且将结果作为字典返回的游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 定义要执行的SQL语句
sql = """
CREATE TABLE USER1 (
id INT auto_increment PRIMARY KEY ,
name CHAR(10) NOT NULL UNIQUE,
age TINYINT NOT NULL
)ENGINE=innodb DEFAULT CHARSET=utf8;
"""
# 执行SQL语句
cursor.execute(sql)
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第64张

 

注意:

charset=“utf8”,编码不要写成"utf-8"

数据库版登录

Python连接MySQL数据库之pymysql模块使用 随笔 第65张

Python连接MySQL数据库之pymysql模块使用 随笔 第66张

  

 

增删改查操作

 

Python连接MySQL数据库之pymysql模块使用 随笔 第67张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
# 执行SQL语句
cursor.execute(sql, [username, age])
# 提交事务
conn.commit()
cursor.close()
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第68张 Python连接MySQL数据库之pymysql模块使用 随笔 第69张 Python连接MySQL数据库之pymysql模块使用 随笔 第70张

Python连接MySQL数据库之pymysql模块使用 随笔 第71张

mysql端:

Python连接MySQL数据库之pymysql模块使用 随笔 第72张

 

Python连接MySQL数据库之pymysql模块使用 随笔 第73张

  

插入数据失败回滚

Python连接MySQL数据库之pymysql模块使用 随笔 第74张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
    # 执行SQL语句
    cursor.execute(sql, [username, age])
    # 提交事务
    conn.commit()
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()
cursor.close()
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第75张 Python连接MySQL数据库之pymysql模块使用 随笔 第76张 Python连接MySQL数据库之pymysql模块使用 随笔 第77张 Python连接MySQL数据库之pymysql模块使用 随笔 第78张

 

获取插入数据的ID(关联操作时会用到)

Python连接MySQL数据库之pymysql模块使用 随笔 第79张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
username = "Alex"
age = 18
try:
    # 执行SQL语句
    cursor.execute(sql, [username, age])
    # 提交事务
    conn.commit()
    # 提交之后,获取刚插入的数据的ID
    last_id = cursor.lastrowid
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()
cursor.close()
conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第80张

Python连接MySQL数据库之pymysql模块使用 随笔 第81张

Python连接MySQL数据库之pymysql模块使用 随笔 第82张 

Python连接MySQL数据库之pymysql模块使用 随笔 第83张

 

批量执行

Python连接MySQL数据库之pymysql模块使用 随笔 第84张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
data = [("Alex", 18), ("Egon", 20), ("Yuan", 21)]
try:
    # 批量执行多条插入SQL语句
    cursor.executemany(sql, data)
    # 提交事务
    conn.commit()

except Exception as e: # 有异常,回滚事务 conn.rollback() cursor.close() conn.close()
Python连接MySQL数据库之pymysql模块使用 随笔 第85张 Python连接MySQL数据库之pymysql模块使用 随笔 第86张 Python连接MySQL数据库之pymysql模块使用 随笔 第87张 Python连接MySQL数据库之pymysql模块使用 随笔 第88张 Python连接MySQL数据库之pymysql模块使用 随笔 第89张

由于数据库的编码格式不一样所以出现乱码:

创建数据库的时候指定编码需要:

Python连接MySQL数据库之pymysql模块使用 随笔 第90张

创建列表的时候也要指定一下,避免乱码:

Python连接MySQL数据库之pymysql模块使用 随笔 第91张

 

Python连接MySQL数据库之pymysql模块使用 随笔 第92张

 

 

Python连接MySQL数据库之pymysql模块使用 随笔 第93张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
sql = "DELETE FROM USER1 WHERE id=%s;"
try:
    cursor.execute(sql, [4])
    # 提交事务
    conn.commit()
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()
cursor.close()
conn.close()

Python连接MySQL数据库之pymysql模块使用 随笔 第94张 Python连接MySQL数据库之pymysql模块使用 随笔 第95张

 

Python连接MySQL数据库之pymysql模块使用 随笔 第96张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 修改数据的SQL语句
sql = "UPDATE USER1 SET age=%s WHERE name=%s;"
username = "Alex"
age = 80
try:
    # 执行SQL语句
    cursor.execute(sql, [age, username])
    # 提交事务
    conn.commit()
except Exception as e:
    # 有异常,回滚事务
    conn.rollback()
cursor.close()
conn.close()

Python连接MySQL数据库之pymysql模块使用 随笔 第97张 Python连接MySQL数据库之pymysql模块使用 随笔 第98张

 

Python连接MySQL数据库之pymysql模块使用 随笔 第99张
#查询操作

import pymysql  #导入 pymysql  
  
#打开数据库连接  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)  
  
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
  
#1.查询操作  
# 编写sql 查询语句  user 对应我的表名  
sql = "select * from user"  
try:  
    cur.execute(sql)    #执行sql语句  
  
    results = cur.fetchall()    #获取查询的所有记录  
    print("id","name","password")  
    #遍历结果  
    for row in results :  
        id = row[0]  
        name = row[1]  
        password = row[2]  
        print(id,name,password)  
except Exception as e:  
    raise e  
finally:  
    db.close()  #关闭连接  

 

Python连接MySQL数据库之pymysql模块使用 随笔 第100张

 

查询单条数据

Python连接MySQL数据库之pymysql模块使用 随笔 第101张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 查询数据的SQL语句
sql = "SELECT id,name,age from USER1 WHERE id=1;"
# 执行SQL语句
cursor.execute(sql)
# 获取单条查询数据
ret = cursor.fetchone()
cursor.close()
conn.close()
# 打印下查询结果
print(ret)

Python连接MySQL数据库之pymysql模块使用 随笔 第102张
  
Python连接MySQL数据库之pymysql模块使用 随笔 第103张   

 

 

查询多条数据

Python连接MySQL数据库之pymysql模块使用 随笔 第104张
# 导入pymysql模块
import pymysql
# 连接database
conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 查询数据的SQL语句
sql = "SELECT id,name,age from USER1;"
# 执行SQL语句
cursor.execute(sql)
# 获取多条查询数据
ret = cursor.fetchall()
cursor.close()
conn.close()
# 打印下查询结果
print(ret)

Python连接MySQL数据库之pymysql模块使用 随笔 第105张

 

  
Python连接MySQL数据库之pymysql模块使用 随笔 第106张   

 

 进阶用法

Python连接MySQL数据库之pymysql模块使用 随笔 第107张
# 可以获取指定数量的数据
cursor.fetchmany(3)
# 光标按绝对位置移动1
cursor.scroll(1, mode="absolute")
# 光标按照相对位置(当前位置)移动1
cursor.scroll(1, mode="relative")
Python连接MySQL数据库之pymysql模块使用 随笔 第108张

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄