Python面试题:在 Python 中,如何连接并操作数据库?

在 Python 中,可以使用多种库来连接并操作数据库。常用的库有 sqlite3psycopg2(用于 PostgreSQL)、PyMySQL(用于 MySQL)、SQLAlchemy(一个 ORM 工具,支持多种数据库)。下面以 SQLite 和 MySQL 为例,介绍如何连接并操作数据库。

使用 sqlite3 库操作 SQLite 数据库

  1. 连接数据库
python 复制代码
import sqlite3

# 连接到 SQLite 数据库(如果数据库不存在,会自动创建)
conn = sqlite3.connect('example.db')

# 创建游标对象
cursor = conn.cursor()
  1. 创建表
python 复制代码
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users
                  (id INTEGER PRIMARY KEY AUTOINCREMENT,
                   name TEXT NOT NULL,
                   age INTEGER NOT NULL)''')
  1. 插入数据
python 复制代码
# 插入数据
cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
cursor.execute("INSERT INTO users (name, age) VALUES ('Bob', 25)")

# 提交事务
conn.commit()
  1. 查询数据
python 复制代码
# 查询数据
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()

for row in rows:
    print(row)
  1. 更新数据
python 复制代码
# 更新数据
cursor.execute("UPDATE users SET age = 26 WHERE name = 'Bob'")

# 提交事务
conn.commit()
  1. 删除数据
python 复制代码
# 删除数据
cursor.execute("DELETE FROM users WHERE name = 'Alice'")

# 提交事务
conn.commit()
  1. 关闭连接
python 复制代码
# 关闭游标和连接
cursor.close()
conn.close()

使用 PyMySQL 库操作 MySQL 数据库

  1. 安装 PyMySQL
sh 复制代码
pip install pymysql
  1. 连接数据库
python 复制代码
import pymysql

# 连接到 MySQL 数据库
conn = pymysql.connect(
    host='localhost',
    user='yourusername',
    password='yourpassword',
    database='yourdatabase'
)

# 创建游标对象
cursor = conn.cursor()
  1. 创建表
python 复制代码
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users
                  (id INT AUTO_INCREMENT PRIMARY KEY,
                   name VARCHAR(255) NOT NULL,
                   age INT NOT NULL)''')
  1. 插入数据
python 复制代码
# 插入数据
cursor.execute("INSERT INTO users (name, age) VALUES ('Alice', 30)")
cursor.execute("INSERT INTO users (name, age) VALUES ('Bob', 25)")

# 提交事务
conn.commit()
  1. 查询数据
python 复制代码
# 查询数据
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()

for row in rows:
    print(row)
  1. 更新数据
python 复制代码
# 更新数据
cursor.execute("UPDATE users SET age = 26 WHERE name = 'Bob'")

# 提交事务
conn.commit()
  1. 删除数据
python 复制代码
# 删除数据
cursor.execute("DELETE FROM users WHERE name = 'Alice'")

# 提交事务
conn.commit()
  1. 关闭连接
python 复制代码
# 关闭游标和连接
cursor.close()
conn.close()

使用 SQLAlchemy 库操作数据库

  1. 安装 SQLAlchemy
sh 复制代码
pip install sqlalchemy
  1. 连接数据库
python 复制代码
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 创建数据库引擎
engine = create_engine('sqlite:///example.db', echo=True)

# 创建基类
Base = declarative_base()

# 定义数据表
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String)
    age = Column(Integer)

# 创建数据表
Base.metadata.create_all(engine)

# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
  1. 插入数据
python 复制代码
# 插入数据
new_user = User(name='Alice', age=30)
session.add(new_user)
session.commit()
  1. 查询数据
python 复制代码
# 查询数据
users = session.query(User).all()
for user in users:
    print(user.name, user.age)
  1. 更新数据
python 复制代码
# 更新数据
user = session.query(User).filter_by(name='Alice').first()
user.age = 31
session.commit()
  1. 删除数据
python 复制代码
# 删除数据
user = session.query(User).filter_by(name='Alice').first()
session.delete(user)
session.commit()

这三个示例展示了如何使用 sqlite3PyMySQLSQLAlchemy 库连接并操作数据库。根据具体需求和数据库类型,可以选择合适的库来实现数据库操作。

相关推荐
王中阳Go30 分钟前
字节跳动的微服务独家面经
微服务·面试·golang
IT毕设梦工厂1 小时前
计算机毕业设计选题推荐-在线拍卖系统-Java/Python项目实战
java·spring boot·python·django·毕业设计·源码·课程设计
小诸葛的博客1 小时前
pg入门1——使用容器启动一个pg
数据库
luthane1 小时前
python 实现average mean平均数算法
开发语言·python·算法
码农研究僧1 小时前
Flask 实现用户登录功能的完整示例:前端与后端整合(附Demo)
python·flask·用户登录
Ylucius2 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
凡人的AI工具箱2 小时前
AI教你学Python 第11天 : 局部变量与全局变量
开发语言·人工智能·后端·python
sleP4o2 小时前
Python操作MySQL
开发语言·python·mysql
凌不了云2 小时前
windows环境下安装python第三方包
开发语言·python