温馨提示×

Python在Ubuntu上如何与数据库交互

小樊
49
2025-11-04 15:39:54
栏目: 编程语言

在Ubuntu上使用Python与数据库交互,通常会使用一些流行的数据库适配器或ORM(对象关系映射)库。以下是一些常见的数据库以及如何在Ubuntu上使用Python与之交互的示例:

1. SQLite

SQLite是一个轻量级的数据库,非常适合小型应用和开发。

import sqlite3

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

# 创建一个Cursor对象使用cursor()方法
cursor = conn.cursor()

# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
               (date text, trans text, symbol text, qty real, price real)''')

# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2023-04-01','BUY','RHAT',100,35.14)")

# 提交事务
conn.commit()

# 查询数据
cursor.execute('SELECT * FROM stocks')
for row in cursor.fetchall():
    print(row)

# 关闭Cursor和连接
cursor.close()
conn.close()

2. MySQL

对于MySQL数据库,你可以使用mysql-connector-pythonPyMySQL库。

首先,安装MySQL客户端库和Python适配器:

sudo apt-get install mysql-client
pip install mysql-connector-python

然后,使用以下代码与MySQL数据库交互:

import mysql.connector

# 连接到MySQL数据库
cnx = mysql.connector.connect(user='username', password='password',
                              host='127.0.0.1',
                              database='mydatabase')

# 创建一个Cursor对象
cursor = cnx.cursor()

# 执行SQL查询
query = ("SELECT first_name, last_name FROM employees")
cursor.execute(query)

# 获取查询结果
for (first_name, last_name) in cursor:
    print(f"{first_name} {last_name}")

# 关闭Cursor和连接
cursor.close()
cnx.close()

3. PostgreSQL

对于PostgreSQL,你可以使用psycopg2库。

首先,安装PostgreSQL客户端库和Python适配器:

sudo apt-get install libpq-dev python3-psycopg2

然后,使用以下代码与PostgreSQL数据库交互:

import psycopg2

# 连接到PostgreSQL数据库
conn = psycopg2.connect(dbname="mydatabase", user="username", password="password", host="127.0.0.1")

# 创建一个Cursor对象
cursor = conn.cursor()

# 执行SQL查询
cursor.execute("SELECT version();")

# 获取查询结果
db_version = cursor.fetchone()
print(db_version)

# 关闭Cursor和连接
cursor.close()
conn.close()

4. 使用ORM

ORM库如SQLAlchemy可以让你用Python类的方式来操作数据库,而不需要编写太多SQL语句。

首先,安装SQLAlchemy:

pip install sqlalchemy

然后,你可以定义模型并与数据库交互:

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

# 定义模型
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    nickname = Column(String)

    def __repr__(self):
        return f"<User(name='{self.name}', fullname='{self.fullname}', nickname='{self.nickname}')>"

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

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

# 创建Session类
Session = sessionmaker(bind=engine)

# 创建session对象
session = Session()

# 添加新用户
ed_user = User(name='ed', fullname='Ed Jones', nickname='edspider')
session.add(ed_user)
session.commit()

# 查询用户
for user in session.query(User).order_by(User.name):
    print(user)

以上就是在Ubuntu上使用Python与不同类型的数据库交互的基本方法。记得在实际部署应用时,要确保数据库连接信息的安全性,不要将敏感信息硬编码在代码中。

0