目录
一、数据库介绍
- 概念:一个存放数据的仓库(Database),这个仓库按照一定的数据结构组织、存放、管理数据。
- 分类:
关系型数据库:mysql、sql server、oracle、DB2等
非关系型数据库:redis等 - python操作数据库的方式
pymysql:纯python开发,支持python2和python3,简单易用
二、数据库的基本操作
1.基本操作流程
- 导入包
- 创建连接
- 获取游标
- 执行sql
- 查询操作(select)
- 非查询操作(insert/update/delete)
- 事务提交(连接对象.commit())
- 事务回滚(连接对象.rollback())
- 关闭游标
- 关闭连接
(1)查询数据
# 导入包
import pymysql
# 创建连接
conn = pymysql.connect(host = "localhost",
port = 3306,
user = "root",
password = "root",
database = "books")
# 获取游标
cursor = conn.cursor()
# 执行sql
sql = "select id, title, `read`, `comment` from t_book;"
cursor.execute(sql)
print(cursor.rowcount) # 获取查询结果的总记录数
print(cursor.fetchone()) # 获取查询结果的第一条数据
cursor.rownumber = 0 # 重置游标的位置
print(cursor.fetchall()) # 获取全部的查询结果
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
执行结果:
3
(1, '射雕英雄传', 12, 34)
((1, '射雕英雄传', 12, 34), (2, '天龙八部', 36, 40), (3, '笑傲江湖', 20,