Python进阶-常用数据库操作
一、MySQL数据库
安装pymysql模块
pip install pymysql
使用方法
# 导入库
import pymysql
# 与数据库建立连接
conn = pymysql.connect(
host="localhost", # 数据库主机地址
port=3306, # 数据库端口
user="root", # 数据库用户名
password="password", # 数据库密码
database="mytest" # 数据库名称
)
# 创建游标对象
cursor = conn.cursor()
# 执行SQL语句
query = "SELECT * FROM users"
cursor.execute(query)
# 如果执行增、删、改操作需要执行commit()方法
# conn.commit()
# 获取查询的全部数据,返回数据为元组类型数据
result = cursor.fetchall()
# 获取表的字段名列表
field_names = [field[0] for field in cursor.description]
print(field_names)
# 循环打印每行的数据
for row in result:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
二、Redis数据
安装redis模块
pip install redis
使用方法
# 导入库
import redis
# 与数据库建立连接
r = redis.Redis(
host='localhost', # 数据库地址
port=6379, # 数据库端口
db=0, # 数据库库号
password='password', # 数据库密码
decode_responses=True # 自动将所有响应从字节串解码为UTF-8编码的字符串
)
# 设置键值对的值
r.set('test', 'ashudaujd')
# 获取键值对的值
r.get('test')
# 删除键值对
r.delete('test')
其他操作
常用操作
# 判断key是否存在,1为存在,0为不存在
exists = r.exists('name')
# 添加到列表
r.lpush('mylist', 'item1')
r.rpush('mylist', 'item2')
# 获取列表,输出: ['item1', 'item2']
items = r.lrange('mylist', 0, -1) print([item.decode('utf-8') for item in items])
# 获取key的TTL
ttl = r.ttl('test')
设置key的TTL
1.添加键时设置 TTL
r.set('mykey', 'value', ex=10)
2.为已存在的键设置 TTL
r.expire('mykey', 20)
三、Postgres数据库
安装pymysql模块
pip install psycopg2
使用方法
Postgres数据库和MySQL数据库的方法除了模块名不一样,其他使用方法基本一致。
# 导入模块
import psycopg2
conn = psycopg2.connect(
host="localhost", # 数据库主机地址
port=5432, # 数据库端口
user="root", # 数据库用户名
password="password", # 数据库密码
database="mytest" # 数据库名称
)
# 创建游标对象
cursor = conn.cursor()
# 执行SQL语句
query = "SELECT * FROM users"
cursor.execute(query)
# 如果执行增、删、改操作需要执行commit()方法
# conn.commit()
# 获取查询的全部数据,返回数据为元组类型数据
result = cursor.fetchall()
# 获取表的字段名列表
field_names = [field[0] for field in cursor.description]
print(field_names)
# 循环打印每行的数据
for row in result:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
四、MongoDB数据库
安装pymysql模块
pip install pymongo
使用方法
# 导入模块
from pymongo import MongoClient
# 创建 MongoClient 对象
client = MongoClient(
host='localhost', # 数据库地址
port=27017, # 数据库端口
username='username', # 数据库用户名
password='password', # 用户名密码
authSource='my_test' # 集合名
)
"""
当然也可以使用连接字符串的形式连接
client = MongoClient('mongodb://username:password@localhost:27017/my_test')
"""
# 选择数据库
db = client['my_test']
# 选择集合名
collection = db['users']
# 查询集合中的文档列表,循环查找所有文档
print(collection.find())
for user in collection.find():
print(user)
# 插入文档
collection.insert_one({"name": "Alice", "age": 30})
# 查询文档
user = collection.find_one({"name": "Alice"})
# 更新文档
collection.update_one({"name": "Alice"}, {"$set": {"age": 31}})
# 删除文档
collection.delete_one({"name": "Alice"})