网站首页 > 教程文章 正文
在 Python 中连接和操作数据库,可以使用以下方法和库来连接常见的关系型数据库如 MySQL 和 PostgreSQL:
1. 连接 MySQL
安装依赖库:
bash
pip install pymysql
示例代码:
python
import pymysql
# 连接 MySQL 数据库
connection = pymysql.connect(
host='localhost', # 数据库地址
user='root', # 用户名
password='your_password',# 密码
database='your_database' # 数据库名
)
try:
with connection.cursor() as cursor:
# 查询数据
cursor.execute("SELECT * FROM your_table")
results = cursor.fetchall()
for row in results:
print(row)
finally:
connection.close() # 关闭连接
2. 连接 PostgreSQL
安装依赖库:
bash
pip install psycopg2
示例代码:
python
import psycopg2
# 连接 PostgreSQL 数据库
connection = psycopg2.connect(
host="localhost",
database="your_database",
user="your_user",
password="your_password"
)
try:
with connection.cursor() as cursor:
# 查询数据
cursor.execute("SELECT * FROM your_table")
results = cursor.fetchall()
for row in results:
print(row)
finally:
connection.close() # 关闭连接
3. SQLAlchemy 通用解决方案
如果你希望使用 ORM(对象关系映射)来更方便地管理数据库,可以使用 SQLAlchemy。
安装依赖库:
bash
pip install sqlalchemy
示例代码:
python
from sqlalchemy import create_engine, Table, MetaData
# 创建数据库引擎(以 MySQL 为例)
engine = create_engine("mysql+pymysql://root:your_password@localhost/your_database")
# 测试连接
with engine.connect() as connection:
result = connection.execute("SELECT * FROM your_table")
for row in result:
print(row)
# 结合 ORM
from sqlalchemy.orm import declarative_base, sessionmaker
Base = declarative_base()
# 定义一个表
class YourTable(Base):
__tablename__ = 'your_table'
id = Column(Integer, primary_key=True)
name = Column(String)
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 查询数据
for item in session.query(YourTable).all():
print(item.name)
4. 数据库连接池:使用 mysql-connector或 psycopg2连接池
如果你的程序需要频繁连接数据库,可以使用连接池来提高效率。
MySQL连接池示例:
python
from mysql.connector import pooling
# 创建连接池
db_pool = pooling.MySQLConnectionPool(
pool_name="mypool",
pool_size=5,
host="localhost",
user="root",
password="your_password",
database="your_database"
)
# 获取连接
connection = db_pool.get_connection()
PostgreSQL连接池示例:
python
from psycopg2 import pool
# 创建连接池
db_pool = pool.SimpleConnectionPool(
1, 10, # 最小和最大连接数
host="localhost",
database="your_database",
user="your_user",
password="your_password"
)
# 获取连接
connection = db_pool.getconn()
小贴士
- 配置文件管理: 将数据库配置存储在 .env 文件中,使用 dotenv 加载配置。
- 安全性: 避免直接在代码中写明密码,优先使用环境变量。
- 防止 SQL 注入: 使用参数化查询,避免直接拼接 SQL 字符串。
猜你喜欢
- 2025-01-10 AI编程之手把手教你在CentOS安装Postgresql的Vector向量数据库
- 2025-01-10 postgresql在centos安装
- 2025-01-10 PostgreSQL技术内幕13:PostgreSQL通讯协议
- 2025-01-10 等保2.0测评:PostgreSQL数据库
- 2025-01-10 PostgreSQL技术内幕10:PostgreSQL事务原理解析-日志模块介绍
- 2025-01-10 基于patroni+etcd打造可自动故障转移的PostgreSQL集群
- 2025-01-10 新手如何快速搭建多套PostgreSQL集群
- 2025-01-10 PostgreSQL是不是你的下一个JSON数据库?
- 2025-01-10 轻松入门PostgreSQL:安装和设置数据库的完整指南!
- 2025-01-10 PostgreSQL、MySQL 数据库被入侵究竟有多么普遍?有人做了一项实验
- 05-08云虚拟电脑与操作云电脑:相同还是不同?
- 05-08【三.丰.云】免费虚拟主机和免费云服务器,真的不错
- 05-08三丰云免费虚拟主机和云服务器评测
- 05-08阿贝云:免费的虚拟主机和云服务器,让我爱上云计算
- 05-08云服务器与虚拟主机的区别解析(云服务器与虚拟主机的区别解析图)
- 05-08(可以搭建游戏无盘)推荐一个免费云服务器,免费虚拟主机
- 05-08【阿贝云】免费云主机,免费虚拟主机
- 05-08免费云服务器和虚拟主机(免费云服务器和虚拟主机的区别)
- 最近发表
- 标签列表
-
- location.href (44)
- document.ready (36)
- git checkout -b (34)
- 跃点数 (35)
- 阿里云镜像地址 (33)
- qt qmessagebox (36)
- md5 sha1 (32)
- mybatis plus page (35)
- semaphore 使用详解 (32)
- update from 语句 (32)
- vue @scroll (38)
- 堆栈区别 (33)
- 在线子域名爆破 (32)
- 什么是容器 (33)
- sha1 md5 (33)
- navicat导出数据 (34)
- 阿里云acp考试 (33)
- 阿里云 nacos (34)
- redhat官网下载镜像 (36)
- srs服务器 (33)
- pico开发者 (33)
- https的端口号 (34)
- vscode更改主题 (35)
- 阿里云资源池 (34)
- os.path.join (33)