linux

Linux下Python与数据库的交互

小樊
85
2024-08-07 01:12:15
栏目: 编程语言

在Linux下,Python可以通过多种方式与数据库进行交互,其中常用的方式包括使用Python的数据库模块(如MySQLdb、psycopg2等)或者使用ORM框架(如SQLAlchemy)。

以下是一个使用Python的MySQLdb模块连接MySQL数据库的示例代码:

import MySQLdb

# 连接到MySQL数据库
db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="test")

# 创建一个游标对象
cursor = db.cursor()

# 执行SQL查询
cursor.execute("SELECT * FROM table_name")

# 获取查询结果
results = cursor.fetchall()
for row in results:
    print(row)

# 关闭游标和数据库连接
cursor.close()
db.close()

另外,如果使用ORM框架,可以简化与数据库的交互过程,以下是一个使用SQLAlchemy连接MySQL数据库的示例代码:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 创建一个引擎对象
engine = create_engine('mysql://root:password@localhost/test')

# 创建一个基类
Base = declarative_base()

# 定义一个数据模型类
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)

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

# 创建一个会话类
Session = sessionmaker(bind=engine)
session = Session()

# 查询数据
users = session.query(User).all()
for user in users:
    print(user.name)

# 关闭会话
session.close()

无论是使用数据库模块还是ORM框架,Python都可以方便地与数据库进行交互并执行各种操作。

0
看了该问题的人还看了