Python数据库编程(SQLite3和MySQL)

Python数据库编程
(一)SQLite3数据库
一、操作SQLite3数据库
从Python3.x版本开始,在标准库中已经内置了SQLite3模块,它可以支持SQLite3数据库访问和相关的数据库操作。在需要操作SQLite3数据库使,只需在程序中导入SQLite3模块即可。Python语言操作SQLite3数据库的基本流程如所示:
– 导入相关库或模块(SQLite3),使用connect()连接数据库并获取数据库连接对象。它提供了以下方法:
.cursor():该方法用来处理一个游标对象
.commit():该方法用来处理事务提交
.rollback():该方法用来处理事务回滚
.close():该方法用来关闭一个数据库连接
– 使用con.cursor()获取游标对象
– 使用游标对象的方法(exectute()executemany()、fetchall()等)来操作数据库,实现插入、修改和删除操作、并查询获取显示相关的记录。在Python程序中,连接函数sqlite3.connect()有如下两个常用参数。

二、使用SQLite3创建表
使用sqlite3模块的connect方法来创建/打开数据库,需要指定数据库路径,不存在则创建一个新的数据库。
con = sqlite3.connect(‘e:/sqllitedb/first.db’)
实例:

# 操作SQLite3创建表

"""
步骤:
    1.导入模块
    2.创建连接 sqlite3.connect()
    3.创建游标对象
    4.编写创建表的SQL语句
    5.执行SQL语句
    6.关闭游标,关闭连接
"""
# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect("D:\学习资料\Python整合\sqlite3Demo\demo.db")
# 创建游标对象
cur = con.cursor()
# 编写创建表的(多条)SQL语句
sql = """create table t_person(
        pno INTEGER PRIMARY KEY autoincrement,
        pname VARCHAR NOT NULL,
        age INTEGER
        )"""
# 执行SQL语句
try:
    cur.execute(sql)
    print("创建表成功")
except Exception as e:
    print(e)
    print("创建表失败")
finally:
    # 关闭游标
    cur.close()
    # 关闭连接,释放资源
    con.close()

三、使用SQLite3插入数据
调用游标对象的execute执行插入的SQL,使用executemany()执行多条SQL语句,使用executemany()比循环使用execute()执行多条SQL语句效率高。
实例:插入一条和多条数据

# 操作SQLite3数据库插入一条数
import sqlite3
con = sqlite3.connect("D:\学习资料\Python整合\sqlite3Demo\demo.db")
cur = con.cursor()
sql = "insert into t_person(pname,age) values(?,?)"
try:
    cur.execute(sql, ("张三", 21))
    # 提交事务
    con.commit()
    print("插入成功")
except Exception as e:
    print(e)
    print("插入失败")
    # 回滚事务
    con.rollback()
finally:
    cur.close()
    con.close()

# 操作SQLite3数据库插入多条数据
import sqlite3
con = sqlite3.connect("D:\学习资料\Python整合\sqlite3Demo\demo.db")
cur = con.cursor()
sql = "insert into t_person(pname,age) values(?,?)"
try:
    cur.executemany(sql, [("郭辉", 20), ("小明", 19), ("小花", 18)])
    # 提交事务
    con.commit()
    print("插入多条数据成功")
except Exception as e:
    print(e)
    print("插入多条数据失败")
    # 回滚事务
    con.rollback()
finally:
    cur.close()
    con.close()

四、操作SQLite3查询数据
查询数据,游标对象提供了fetchall()和fetchone()方法。 fetchall()方法获取所有数据,返回一个列表。fetchone()方法获取其中一个结果,返回一个元组。
实例:操作SQLite3查询一条或所有的数据

# 操作SQLite3数据库查询所有数据
import sqlite3
con = sqlite3.connect("D:\学习资料\Python整合\sqlite3Demo\demo.db")
cur = con.cursor()
sql = "select * from t_person"
try:
    cur.execute(sql)
    # 查找所有
    # 获取结果集
    person_all = cur.fetchall()
    print(person_all)
    for t in person_all:
        print(t)
except Exception as e:
    print(e)
    print("查询失败")
    # 回滚事务
    con.rollback()
finally:
    cur.close()
    con.close()


# 操作SQLite3数据库查询一条数据
import sqlite3
con = sqlite3.connect("D:\学习资料\Python整合\sqlite3Demo\demo.db")
cur = con.cursor()

sql = "select * from t_person"
try:
    cur.execute(sql)
    # 获取一条数据
    person_one = cur.fetchone()
    print(person_one)
    for t in person_one:
        print(t)
except Exception as e:
    print(e)
    print("查询该条数据失败")
    con.rollback()
finally:
    cur.close()
    con.close()

五、操作SQLite3修改数据
实例:

# 操作SQLite3数据库修改数据
import sqlite3
con = sqlite3.connect("D:\学习资料\Python整合\sqlite3Demo\demo.db")
cur = con.cursor()
sql1 = "update t_person set pname=? where pno=?"
sql2 = "select * from t_person"
try:
    cur.execute(sql1, ("小红", 1))
    print("修改数据成功")
    #提交事务
    cur.execute(sql2)
    con.commit()
    person_all = cur.fetchall()
    for i in person_all:
        print(i)
except Exception as e:
    print(e)
    print("修改数据失败")
    con.rollback()
finally:
    cur.close()
    con.close()

六、操作SQLite3删除数据
实例:

# 操作SQLite3数据库修改数据
import sqlite3
con = sqlite3.connect("D:\学习资料\Python整合\sqlite3Demo\demo.db")
cur = con.cursor()
sql1 = "delete from t_person where pno=?"
sql2 = "select * from t_person"
try:
    cur.execute(sql1, (2,))
    #提交事务
    con.commit()
    print("删除数据成功")
    cur.execute(sql2)
    person_all = cur.fetchall()
    for i in person_all:
        print(i)
except Exception as e:
    print(e)
    print("删除数据失败")
    con.rollback()
finally:
    cur.close()
    con.close()

(二)MySQL数据库
一、下载MySQL
https://www.mysql.com
下载社区版

二、安装MySQL
1.运行.msi安装版文件
2.勾选复选框同意协议,点击next
3.勾选‘custom’自定义安装,点击next
4.选择产品或特色,将MySQL Servers->MySQL Server-> MySQL Server 8.0下的MySQL Server 8.0.17-x64添加到需要下载的窗口中,点击next
5.选择安装路径,一般为默认安装路径
6.点击execute进行下载刚才添加到产品框的对应软件,点击next
7.点击next,配置MySQL(一般选择默认协议和端口),点击两次next
8.设置MySQL密码,点击next,设置MySQL服务器名称,点击next
9.点击execute进行应用配置,最后点击Finish、next、Finish

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

1.搭建PyMySQL环境
在使用PyMySQL之前,需要确保PyMySQL已安装。如果还未安装,可以使用以下命令安装最新版的PyMySQL。

pip install PyMySQL

2.创建数据库表
在Python程序中,可以使用execute()在数据库中创建一个新表,示例如下:

# 创建数据库表
# 导入pymysql模块
import pymysql
# 创建连接
con = pymysql.connect(host="localhost", user="root", password="rgyrzdt555", database="python_db", port=3306)
# 创建游标对象
cur = con.cursor()
# 编写创建表的sql
sql = """
    create table h_student(
    sno INT PRIMARY KEY auto_increment,
    sname varchar(30) NOT NULL,
    age int(2),
    score float(3, 1)
    )
"""
try:
    # 执行创建表的SQL
    cur.execute(sql)
    print("创建表成功")
except Exception as e:
    print(e)
    print("创建表失败")
finally:
    # 关闭连接
    con.close()

3.数据库插入数据操作
实例:向student表里面插入一条或多条数据信息
# 在数据库表中插入一条数据

  	import pymysql
    con = pymysql.connect(host="localhost", user="root", password="rgyrzdt555", port=3306, database="python_db")
    cur = con.cursor()
    sql = "insert into t_student(sname, age, score) values(%s, %s, %s)"
    
    try:
        cur.execute(sql, ("GuoHui", 21, 99))
        con.commit()
        print("数据插入成功")
    except Exception as e:
        print(e)
        con.rollback()
        print("数据插入失败")
    finally:
        cur.close()
        con.close()
    
    # 在数据库表中插入多条数据
    import pymysql
    con = pymysql.connect(host="localhost", user="root", password="rgyrzdt555", port=3306, database="python_db")
    cur = con.cursor()
    sql = "insert into t_student(sname, age, score) values(%s, %s, %s)"
    
    try:
        cur.executemany(sql,[("小明", 16, 78), ("小红", 17, 88), ("小郭", 19, 99), ("小雨", 20, 97)])
        con.commit()
        print("数据插入成功")
    except Exception as e:
        print(e)
        con.rollback()
        print("数据插入失败")
    finally:
        cur.close()
        con.close()

4.数据库查询操作
Python查询MySQL使用fetchone()方法获取的单条数据,使用fetchall()方法获取多条数据。
fetchone():该方法下获取下一个查询结果集。结果集是一个对象
fetchall():接收全部的返回结果行。
rowcount():这是一个只读属性,并返回执行execute()方法后影响的行数。
实例:单个查询、查询所有和按条件查询

# 数据库查询操作

# 单个查询操作
# fetchone()方法
import pymysql
con = pymysql.connect(host="localhost", user="root", password="rgyrzdt555", database="python_db", port=3306)
cur = con.cursor()
sql = "select * from t_student"
# sql = "select * from t_student where age=19"
try:
    cur.execute(sql)
    # 处理结果集
    student = cur.fetchone()
    sno = student[0]
    sname = student[1]
    age = student[2]
    score = student[3]
    print("sno:", sno, "sname:", sname, "age:", age, "score:", score)
except Exception as e:
    print(e)
    print("查询所有数据失败")
finally:
    con.close()



# 查询所有和按条件查询
# fetchall()方法
import pymysql
con = pymysql.connect(host="localhost", user="root", password="rgyrzdt555", database="python_db", port=3306)
cur = con.cursor()
sql = "select * from t_student"
# sql = "select * from t_student where age=19"
try:
    cur.execute(sql)
    # 处理结果集
    students = cur.fetchall()
    for p in students:
        sno = p[0]
        sname = p[1]
        age = p[2]
        score = p[3]
        print("sno:", sno, "sname:", sname, "age:", age, "score:", score)
except Exception as e:
    print(e)
    print("查询所有数据失败")
finally:
    con.close()

5.数据库更新操作
在Python程序中,可以使用update语句来更新数据库中的数据信息。
实例:修改数据库数据

# 数据库更新操作
import pymysql
con = pymysql.connect(host="127.0.0.1", user="root", password="rgyrzdt555", database="python_db", port=3306)
cur = con.cursor()
sql = "update t_student set sname=%s where sno=%s"
try:
    cur.execute(sql, ("guofutang", 1))
    con.commit()
    print("修改成功")
except Exception as e:
    print(e)
    con.rollback()
    print("修改失败")
finally:
    con.close()

6.数据库删除操作
使用delete加条件来删除数据
实例:删除数据

# 数据库删除操作
import pymysql
con = pymysql.connect(host="127.0.0.1", user="root", password="rgyrzdt555", database="python_db", port=3306)
cur = con.cursor()
sql = "delete from t_student where sno=%s"
try:
    cur.execute(sql, 3)
    con.commit()
    print("删除成功")
except Exception as e:
    print(e)
    con.rollback()
    print("删除失败")
finally:
    con.close()

Python数据库编程(SQLite3和MySQL)_第1张图片
【公众号:绿哨网络安全】

你可能感兴趣的:((新手老鸟)python干货,MySQL,SQLite3,Python数据库编程,Python,数据库)