【Python】15. 数据库编程

1 操作SQLite3数据库

从Python3.x版本开始,在标准库中已经内置了SQLlite3模块,它可以支持SQLite3数据库的访问和相关的数据库操作。在需要操作SQLite3数据库数据时,只须在程序中导入SQLite3模块即可。Python语言操作SQLite3数据库的基本流程如下所示。

(1) 导入相关库或模块(SQLite3)。
(2) 使用connect()连接数据库并获取数据库连接对象。它提供了以下方法:
.cursor() 方法来创建一个游标对象
.commit() 方法来处理事务提交
.rollback() 方法来处理事务回滚
.close() 方法来关闭一个数据库连接
(3) 使用con.cursor()获取游标对象。
(4) 使用游标对象的方法(execute()、executemany()、fetchall()等)来操作数据库,实现插入、修改和删除操作,并查询获取显示相关的记录。在Python程序中,连接函数sqlite3.connect()有如下两个常用参数。
database:表示要访问的数据库名。
timeout:表示访问数据的超时设定。
(5) 使用close()关闭游标对象和数据库连接。数据库操作完成之后,必须及时调用其close()方法关闭数据库连接,这样做的目的是减轻数据库服务器的压力。

1.1 使用SQLite3创建表

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

'''
1.导入sqlite3模块
2.创建连接sqlite3.connect()
3.创建游标对象
4.编写创建表的sql语句
5.执行sql
6.关闭连接
'''
import sqlite3

# 创建链接
con = sqlite3.connect(r"C:\sqlite3Demo\demo.db")
# 创建游标对象
cur=con.cursor()
# 编写创建表的sql语句
sql='''create table t_person(
        pno INTEGER primary key autoincrement,
        pname VARCHAR not null,
        age INTEGER 
)'''
try:
    # 执行sql语句
    cur.execute(sql)
    print("创建表成功")
except Exception as e:
    print(e)
    print("创建表失败")

finally:
    # 关闭游标
    cur.close()
    # 关闭连接
    con.close()

1.2 使用SQLite3插入数据

调用游标对象的execute执行插入的sql,使用executemany()执行多条sql语句,使用executmany()比循环使用excute()执行多条sql语句效率高。
【示例】使用SQLite3插入一条数据

# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect(r"C:\sqlite3Demo\demo.db")
# 创建游标对象
cur = con.cursor()
# 编写插入sql
sql='insert into t_person(pname,age)values (?,?)'
try:
    # 执行sql
    cur.execute(sql,("张三",24))
    # 提交事务
    con.commit()
    print('插入数据成功')
except Exception as e:
    print(e)
    con.rollback()    # 回滚
    print("插入数据失败")
finally:
    # 关闭游标连接
    cur.close()
    # 关闭数据库连接
    con.close()

【示例】使用SQLite3插入多条数据

# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect(r"C:\sqlite3Demo\demo.db")
# 创建游标对象
cur = con.cursor()
# 编写插入sql
sql='insert into t_person(pname,age)values (?,?)'
try:
    # 执行插入多条数据的sql
    cur.executemany(sql,[("小李",23),('小花',34)])
    # 提交事务
    con.commit()
    print('插入多条数据成功')
except Exception as e:
    print(e)
    con.rollback()    # 回滚
    print("插入多条数据失败")
finally:
    # 关闭游标连接
    cur.close()
    # 关闭数据库连接
    con.close()

1.3 使用SQLite3查询数据

查询数据,游标对象提供了fetchall()和fetchone()方法 。fetchall()方法获取所有数据,返回一个列表。fetchone()方法获取其中一个结果,返回一个元组。
【示例】fetchall()查询所有数据

# 导入模块
import sqlite3

# 创建连接
con = sqlite3.connect(r"C:\sqlite3Demo\demo.db")
# 创建游标对象
cur = con.cursor()
# 创建查询sql
sql = 'select* from t_person'
try:
    cur.execute(sql)
    # 获取结果集
    person_all = cur.fetchall()
    # print(person_all)
    for person in person_all:
        print(person)
except Exception as e:
    print(e)
    print('查询数据失败')
finally:
    # 关闭游标连接
    cur.close()
    # 关闭数据库连接
    con.close()

执行结果:
(1, ‘张三’, 24)
(2, ‘小李’, 23)
(3, ‘小花’, 34)

在这里插入代码片

【示例】fetchone()查询一条数据

# 2 导入模块
import sqlite3

# 3 创建连接
con = sqlite3.connect(r"C:\sqlite3Demo\demo.db")
# 4 创建游标对象
cur = con.cursor()
# 5 创建查询sql
sql = 'select* from t_person'
try:
    cur.execute(sql)
    # 获取结果集,获取一条数据
    person = cur.fetchone()
    print(person)
except Exception as e:
    print(e)
    print('查询数据失败')
finally:
    # 关闭游标连接
    cur.close()
    # 关闭数据库连接
    con.close()

执行结果:

(1, '张三', 24)

5.1 使用sqlite3修改数据

【示例】修改数据

# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect(r"C:\sqlite3Demo\demo.db")
# 创建游标
cur=con.cursor()
# 编写修改的SQL语句
sql = 'update t_person set pname=? where pno=?'    如果报错,重新敲一下这条
# 执行sql
try:
    cur.execute(sql, ("小张", 1))
    # 提交事务
    con.commit()
    print("修改成功")
except Exception as e:
    print(e)
    print("修改失败")
    con.rollback()
finally:
    # 关闭游标连接
    cur.close()
    # 关闭数据库连接
    con.close()

执行结果:

(1, '小张', 24)

【示例】删除数据

# 导入模块
import sqlite3
# 创建连接
con = sqlite3.connect(r"C:\sqlite3Demo\demo.db")
# 创建游标
cur=con.cursor()
# 编写删除的SQL语句
sql = 'delete from t_person where pno=?'
# 执行sql
try:
    cur.execute(sql, (1,))
    # 提交事务
    con.commit()
    print("删除成功")
except Exception as e:
    print(e)
    print("删除失败")
    con.rollback()
finally:
    # 关闭游标连接
    cur.close()
    # 关闭数据库连接
    con.close()

执行结果:

(2, '小李', 23)
(3, '小花', 34)

在上述实例代码中,首先定义查询所有数据、插入数据、修改数据、删除数据的方法。然后,定义主方法中依次建立连接,获取连接的cursor,通过cursor的execute()等方法来执行SQL语句,调用插入记录、更加记录、删除记录的方法。

6 操作MySQL数据库

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

6.1 搭建PyMySQL环境

在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。如果还未安装,我们可以使用以下命令安装最新版的 PyMySQL

 pip  install PyMySQL

【示例】创建表student

import pymysql
try:
    #创建与数据库的连接
    db=pymysql.connect('localhost','root','root','testdb')
    #创建游标对象cursor
    cursor=db.cursor()
    #使用execute()方法执行sql,如果表存在则删除
    cursor.execute('drop table if EXISTS student')
    #创建表的sql
    sql='''
        create table student(
        sno int(8) primary key auto_increment,
        sname varchar(30) not null,
        sex varchar(5) ,
        age int(2),
        score float(3,1)
        )
    '''
    cursor.execute(sql)
except:
    print('创建表失败')
finally:
    #关闭数据库连接
    db.close()

6.2 数据库插入操作

在Python程序中,可以使用SQL语句向数据库中插入新的数据信息。
【示例】向student表中插入数据信息

import pymysql
#创建与数据库的连接
db=pymysql.connect('localhost','root','root','testdb')
#创建游标对象cursor
cursor=db.cursor()
#插入sql语句
sql='''
    insert into student(sname,sex,age,score) values(%s,%s,%s,%s)
'''
try:
    #执行sql语句
    cursor.execute(sql,('李四','woman',25,99.6))
    #提交事务
    db.commit()
    print('插入成功')
except Exception as e:
    print(e)
    #如果出现异常,回滚
    db.rollback()
    print('插入失败')
finally:
    #关闭数据库连接
    db.close()

【示例】向student表同时插入多条数据

import pymysql
#创建与数据库的连接
db=pymysql.connect('localhost','root','root','testdb')
#创建游标对象cursor
cursor=db.cursor()
#插入sql语句
sql='''
    insert into student(sname,sex,age,score) values(%s,%s,%s,%s)
'''
args=[('王五','woman',22,98.6),('赵六','man',21,99.1)]
try:
    #执行sql语句
    cursor.executemany(sql,args)
    #提交事务
    db.commit()
    print('插入成功')
except Exception as e:
    print(e)
    #如果出现异常,回滚
    db.rollback()
    print('插入失败')
finally:
    #关闭数据库连接
    db.close()

6.3 数据库查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
fetchall(): 接收全部的返回结果行.
rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
【示例】查询学生 年龄大于等于23的所有学生信息

import pymysql
#创建与数据库的连接
db=pymysql.connect('localhost','root','root','testdb')
#创建游标对象cursor
cursor=db.cursor()
#查询年龄大于等于23的所有学生信息
sql='select * from student where age>=23'
try:
    #执行sql
    cursor.execute(sql)
    #获取查询结果
    results=cursor.fetchall()
    for row in results:
        sno=row[0]
        sname=row[1]
        sex=row[2]
        age=row[3]
        score=row[4]
        #输出
        print('sno:',sno,'sname:',sname,'sex:',sex,'age:',age,'score:',score)
except Exception as e:
    print(e)
    print('查询失败')
finally:
    db.close()

6.4 数据库更新操作

在Python程序中,可以使用update语句更新数据库中数据信息。
【示例】更新数据库中的数据

import pymysql
#创建与数据库的连接
db=pymysql.connect('localhost','root','root','testdb')
#创建游标对象cursor
cursor=db.cursor()
#将sno=5的学生成绩修改为99.5
sql='update student set score=%s where sno=%s'
try:
    #执行sql
    cursor.execute(sql,(99.5,5))
    #提交数据
    db.commit()
    print('修改成功')
except:
    print('修改失败')
    db.rollback()
finally:
    db.close()

6.5 数据库删除操作

在Python程序中,可以使用delete语句删除数据库中的数据信息
【示例】删除年龄小于22的学生

import pymysql
#创建与数据库的连接
db=pymysql.connect('localhost','root','root','testdb')
#创建游标对象cursor
cursor=db.cursor()
#删除sql
sql='delete from student where age < 22'
try:
    #执行sql语句
    cursor.execute(sql)
    #提交事务
    db.commit()
    print('删除数据成功')
except:
    db.rollback()
    print('删除数据失败')
finally:
    #关闭连接
    db.close()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LouHerGetUp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值