> 文档中心 > Python操作常用数据库

Python操作常用数据库

Python操作常用数据库

  • 前言
  • 简介
  • SQLite
    • 连接SQLite
    • 创建数据
  • MySQL
    • mysql-connector操作MySQL
      • 创建数据表
    • pymysql操作MySQL
  • MongoDB
    • 连接MongoDB
  • Redis
    • 连接Redis

前言

本文是个人使用Python操作常用数据库的学习笔记,由于水平有限,难免出现错漏,敬请批评改正。

简介

  • 数据库可以按照存储模型、关系型/非关系型来进行分类。
  • 关系型数据库:指采用了关系模型来组织数据的数据库。
    关系模型指的就是二维表格模型,而一个关系型数据库就是由二维表及其之间的联系所组成的一个数据组织。
  • 当今主流的关系型数据库:Oracle,Microsoft SQL Server,MySQL等。
  • 非关系型数据库:指非关系型的,分布式的,且一般不保证遵循ACID原则的数据存储系统。非关系型数据库以键值对存储,且结构不固定,每一个元组可以有不一样的字段,每个元组可以根据需要增加一些自己的键值对,不局限于固定的结构,可以减少一些时间和空间的开销。
  • 当今主流的非关系型数据库:Redis, Amazon DynamoDB, Memcached、MongoDB等。
  • 常用数据库排名,以下数据来源于DB-Engines在这里插入图片描述
    在这里插入图片描述

SQLite

  • SQLite 是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在 iOS 和 Android的APP中都可以集成。Python 就内置了SQLite3,所以,在 Python 中使用 SQLite,不需要安装任何东西,直接使用。
  • Python 定义了一套操作数据库的 API接口,任何数据库要连接到 Pyton,只需要提供符合 Python标准的数据库驱动即可。由于SQLite的驱动内置在 Python 标准库中,因此可以直接来换作SQLite数据库。
  • 在 Python 中操作数据库时,要先导入数据库对应的驱动,然后通过Connection对象和Cursor对象操作数据。在数据库操作完毕之后,要确保打开的 Connection对象和 Cursor对象都正确地被关闭,否则,资源就会泄露。

连接SQLite

# python连接SQLiteimport sqlite3import os# 连接到SQLite数据库,如果数据库文件test.db不存在,会自动创建conn=sqlite3.connect('test.db')# 创建一个Cursorcursor=conn.cursor()

创建数据表

# 执行SQL语句,创建user表cursor.execute('create table IF NOT EXISTS user(id varchar(20) primary key,name varchar(20))')

# 执行SQL语句,插入记录li=["Mary","John","Tom"]for i in enumerate(li,start=1): # start=1表示序号从1开始    cursor.execute('insert into user (id, name) values (?,?)',(i[0],i[1])) # 增# 执行查询语句:cursor.execute('select * from user')# 获取结果列表values=cursor.fetchall()print("查询整个表数据:",values)
查询整个表数据: [('1', 'Mary'), ('2', 'John'), ('3', 'Tom')]

# 执行删除语句:cursor.execute('delete from user where id=?',('1',)) # 1->?# 执行查询语句:cursor.execute('select * from user')# 获取结果列表values=cursor.fetchall()print("查询整个表数据:",values)
查询整个表数据: [('2', 'John'), ('3', 'Tom')]

# 执行修改语句:cursor.execute('update user set name="Freeman" WHERE id=?',('3',)) # 3->?# 执行查询语句:cursor.execute('select * from user')# 获取结果列表values=cursor.fetchall()print("查询整个表数据:",values)
查询整个表数据: [('2', 'John'), ('3', 'Freeman')]

# 执行查询语句:cursor.execute('select * from user')# 获取结果列表values=cursor.fetchall()print("查询整个表数据:",values)# 执行查询id为2语句:cursor.execute('select * from user where id=?',('2',)) # 2->?# 获取结果列表values=cursor.fetchall()print("查询表中id为2的数据:",values)# 关闭cursorcursor.close()# 提交事务conn.commit()# 关闭连接conn.close()
查询整个表数据: [('2', 'John'), ('3', 'Freeman')]查询表中id为2的数据: [('2', 'John')]

MySQL

  • MySQL 是最流行的关系型数据库管理系统,在 WEB 应用方面 MySQL 是最好的 RDBMS(Relational Database Management System:关系数据库管理系统)应用软件之一。
  • 可以使用 mysql-connector 来连接使用 MySQL, mysql-connector 是 MySQL 官方提供的驱动器。
  • PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2 中则使用 mysqldb。
  • PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

mysql-connector操作MySQL

# mysql.connector连接MySQLimport mysql.connector conn = mysql.connector.connect(host="localhost",   user="root",   password="123456",   port=3306,   database='testdb',   auth_plugin='mysql_native_password') cursor = conn.cursor()

创建数据表

cursor.execute("CREATE TABLE IF NOT EXISTS websites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), url VARCHAR(255))")

sql = "INSERT INTO websites (name, url) VALUES (%s, %s)"val = [  ('Google', 'https://www.google.com'),  ('Github', 'https://www.github.com'),  ('Taobao', 'https://www.taobao.com'),  ('CSDN', 'https://www.csdn.net')] cursor.executemany(sql, val) # 执行多次插入数据 conn.commit()    # 数据表内容有更新,必须使用到该语句,提交事务 print(cursor.rowcount, "记录插入成功。")# 执行查询语句:cursor.execute('select * from websites')# 获取结果列表values=cursor.fetchall()print("查询整个表数据:",values)
4 记录插入成功。查询整个表数据: [(1, 'Google', 'https://www.google.com'), (2, 'Github', 'https://www.github.com'), (3, 'Taobao', 'https://www.taobao.com'), (4, 'CSDN', 'https://www.csdn.net')]

# 执行删除语句:cursor.execute('delete from websites where id=%s',('2',)) # 2->%s# 执行查询语句:cursor.execute('select * from websites')# 获取结果列表values=cursor.fetchall()print("查询整个表数据:",values)
查询整个表数据: [(1, 'Google', 'https://www.google.com'), (3, 'Taobao', 'https://www.taobao.com'), (4, 'CSDN', 'https://www.csdn.net')]

# 执行修改语句:cursor.execute('update websites set name="淘宝网" WHERE id=%s',('3',)) # 3->%s# 执行查询语句:cursor.execute('select * from websites')# 获取结果列表values=cursor.fetchall()print("查询整个表数据:",values)
查询整个表数据: [(1, 'Google', 'https://www.google.com'), (3, '淘宝网', 'https://www.taobao.com'), (4, 'CSDN', 'https://www.csdn.net')]

cursor.execute('select * from websites')# 获取结果列表values=cursor.fetchall()print("查询整个表数据:",values)# 执行查询id为2语句:cursor.execute('select * from websites where id=%s',('3',)) # 3->%s# 获取结果列表values=cursor.fetchall()print("查询表中id为3的数据:",values)# 关闭cursorcursor.close()# 关闭连接conn.close()
查询整个表数据: [(1, 'Google', 'https://www.google.com'), (3, '淘宝网', 'https://www.taobao.com'), (4, 'CSDN', 'https://www.csdn.net')]查询表中id为3的数据: [(3, '淘宝网', 'https://www.taobao.com')]

pymysql操作MySQL

# 使用pymysql操作MySQLimport pymysql# 连接mysql,connect()方法声明一个MySQL连接对象dbconn = pymysql.connect(host='localhost',user='root', password='123456', port=3306, database='testdb')# 调用cursor()方法获得MySQL的操作游标,利用游标来执行SQL语句cursor = conn.cursor()# 执行sql语句,创建数据库的操作,数据库名叫作maotai,默认编码为UTF-8count = cursor.execute("SELECT * FROM websites")# 调用fetchall()方法获得所有数据data = cursor.fetchall()print('查询整个表数据:\n', data)print('打印执行SQL语句受影响的行数:',count)# 关闭cursorcursor.close()# 关闭连接conn.close()
查询整个表数据: ((1, 'Google', 'https://www.google.com'), (2, 'Github', 'https://www.github.com'), (3, 'Taobao', 'https://www.taobao.com'), (4, 'CSDN', 'https://www.csdn.net'))打印执行SQL语句受影响的行数: 4

MongoDB

  • MongoDB 是目前最流行的 NoSQL 数据库之一,使用的数据类型 BSON(类似 JSON)。
  • Python 要连接 MongoDB 需要 MongoDB 驱动,这里我们使用 PyMongo 驱动来连接。

连接MongoDB

import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/")dblist = client.list_database_names() # 查看已有的数据库print(dblist)
['Test', 'admin', 'config', 'images360', 'local', 'mytest', 'runoobdb', 'taobao', 'taobaomeishi', 'tutorial', 'weibo']

注意:在 MongoDB 中,数据库只有在内容插入后才会创建.

# 在 MongoDB 中,数据库只有在内容插入后才会创建.db = client['mytest'] #创建一个数据库 print(db)collection = db['students'] # 创建一个集合print(collection)student = {    'id': '20220101',    'name': 'Jordan',    'age': 20,    'gender': 'male'}result = collection.insert_one(student) # 插入一条数据print(result)students_list = [    {'id': '20220102','name': 'Tom','age': 21,'gender': 'male'},    {'id': '20220103','name': 'John','age': 22,'gender': 'male'},    {'id': '20220104','name': 'Mary','age': 19,'gender': 'female'},    {'id': '20220105','name': 'Freeman','age': 18,'gender': 'male'}]result = collection.insert_many(students_list) # 插入多条数据print(result)print(result.inserted_ids)
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'mytest')Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'mytest'), 'students')[ObjectId('6238738c44d8cba61b1d5451'), ObjectId('6238738c44d8cba61b1d5452'), ObjectId('6238738c44d8cba61b1d5453'), ObjectId('6238738c44d8cba61b1d5454')]

# # 删除result = collection.delete_one({'name': 'Tom'}) # 删除第一条符合条件的数据print(result)print(result.deleted_count) result = collection.delete_many({'age': {'$lt': 20}}) # 删除所有age<25的数据print(result.deleted_count)
12

# 更新或修改condition = {'age': {'$gt': 20}} # 指定查询条件为年龄大于 20result = collection.update_one(condition, {'$inc': {'age': 1}}) # {'$inc': {'age': 1}},表示age+1print(result)print(result.matched_count, result.modified_count)condition = {'age': {'$gt': 20}}result = collection.update_many(condition, {'$inc': {'age': 1}})print(result)print(result.matched_count, result.modified_count)
1 11 1

result = collection.find_one({'name': 'Tom'}) # 查询一条print(type(result))print(result)results = collection.find({'age': 20}) # 查询所有满足条件的数据print(results)for result in results:    print(result)    results = collection.find({'age': {'$gt': 20}}) # 用正则表达式查询所有age大于 20 的数据print(results)for result in results:    print(result)    results = collection.find({'name': {'$regex': '^T.*'}}) # 用正则表达式查询所有name以T开头的数据print(results)for result in results:    print(result)
None{'_id': ObjectId('6238738c44d8cba61b1d5450'), 'id': '20220101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}{'_id': ObjectId('6238738c44d8cba61b1d5452'), 'id': '20220103', 'name': 'John', 'age': 24, 'gender': 'male'}

Redis

  • REmote DIctionary Server(Redis) 是一个由 Salvatore Sanfilippo 写的 key-value 存储系统,是跨平台的非关系型数据库。
  • Redis 是一个开源的使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式、可选持久性的键值对(Key-Value)存储数据库,并提供多种语言的 API。
  • Redis 通常被称为数据结构服务器,因为值(value)可以是字符串(String)、哈希(Hash)、列表(list)、集合(sets)和有序集合(sorted sets)等类型。
  • Redis (REmote Dletionary Server)提供两个类 Redis 和 Strictredis用于实现 Redis 的命令,Strictredis用于实现大部分官方的命令,并使用官方的语法和命令,Redis是 Strictredis的子类,用于向后兼容旧版本的 Redis-Py。
  • Redis 连接实例是线程安全的,可以将 Redis 连接实例设置为一个全局变量,直接使用。如果需要另一个Redis 实例(Redis数据库)时,就需要重新创建 Redis 连接实例来获取一个新的连接。同理,Python的 Redis 没有实现 SELECT 命令。

连接Redis

import redisfrom redis import StrictRedis# 声明了一个StrictRedis对象连接redis = StrictRedis(host='localhost', port=6379, db=0, password='') # 连接方法一# redis = redis.Redis(host='localhost', port=6379, db=0, password='') # 连接方法二# 调用set()方法,设置一个键值对redis.set('name', 'Tom')# get()将其获取print(redis.get('name'))
b'Tom'
# 使用连接池,可以实现多个Redis实例共享一个连接池from redis import StrictRedis, ConnectionPoolpool = ConnectionPool(host='localhost', port=6379, db=0,password='')redis = StrictRedis(connection_pool=pool)# 调用set()方法,设置一个键值对redis.set('gender', 'male')# get()将其获取print(redis.get('gender'))
b'male'

更多精彩内容,可点击进入Python日常小操作专栏查看