Python操作各种数据库

文章目录

  • MySQL
  • Oracle
  • Redis

MySQL

from mysql.connector import connect

# 连接到服务器
print('连接到mysql服务器...')
db = connect(user="root", passwd="666666", database="talent_directory", use_unicode=True)
print('连接上了!')

# 创建表
cursor = db.cursor()  # 使用cursor()方法获取操作游标
cursor.execute("DROP TABLE IF EXISTS Student")  # 如果存在表Sutdent先删除
cursor.execute("CREATE TABLE Student(ID CHAR(10) NOT NULL, Name CHAR(8), Grade INT )")

# 往表里插入数据
try:
    cursor.execute("""INSERT INTO Student
         VALUES ('001', 'CZQ', 70),
                ('002', 'LHQ', 80),
                ('003', 'MQ', 90),
                ('004', 'WH', 80),
                ('005', 'HP', 70),
                ('006', 'YF', 66),
                ('007', 'TEST', 100)""")
    db.commit()
except Exception as e:
    print("插入数据失败{}".format(e))
    db.rollback()

# 查询数据
try:
    cursor.execute("SELECT * FROM Student")
    results = cursor.fetchall()
    for row in results:
        id_, name, grade = row
        print(id_, name, grade)
except Exception as e:
    print("无法查询到数据{}".format(e))

db.close()  # 最后一定要记得关闭连接
# def deletedb(db):
#     # 使用cursor()方法获取操作游标
#     cursor = db.cursor()
#
#     # SQL 删除语句
#     sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)
#
#     try:
#         # 执行SQL语句
#         cursor.execute(sql)
#         # 提交修改
#         db.commit()
#     except:
#         print('删除数据失败!')
#         # 发生错误时回滚
#         db.rollback()
#
#
# def updatedb(db):
#     # 使用cursor()方法获取操作游标
#     cursor = db.cursor()
#
#     # SQL 更新语句
#     sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % '003'
#
#     try:
#         # 执行SQL语句
#         cursor.execute(sql)
#         # 提交到数据库执行
#         db.commit()
#     except:
#         print('更新数据失败!')
#         # 发生错误时回滚
#         db.rollback()
#
#
# def closedb(db):
#     db.close()
#

Oracle

import cx_Oracle
conn = cx_Oracle.connect('scott/tiger@localhost:1521/orcl')
cursor = conn.cursor()
cursor.execute("SELECT ENAME FROM EMP")
row = cursor.fetchone()
print(row[0])
cursor.close()
conn.close()

Redis

import redis
from redis import StrictRedis

"""
redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维
护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池
"""
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

key, value = 1, {'name': 'xiligey', 'gender': 'male', 'age': 24, 'city': 'BeiJing'}
r.set(key, value)
"""
在Redis中设置值,默认,不存在则创建,存在则修改
参数:
ex,过期时间(秒)
px,过期时间(毫秒)
nx,如果设置为True,则只有name不存在时,当前set操作才执行
xx,如果设置为True,则只有name存在时,当前set操作才执行
"""
r.setex(key, value, 3)  # 设置时间3秒后过期
r.setnx(key, value)  # 只有当key不存在时才执行添加操作
r.get(1)

  • MongoDB

你可能感兴趣的:(#,Python基础)