在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, Stringfrom sqlalchemy.ext.declarative import declarative_basefrom 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都可以方便地与数据库进行交互并执行各种操作。