在Ubuntu上使用Python与数据库进行交互,通常有以下几种方法:
Python标准库中的sqlite3模块:
如果你使用的是SQLite数据库,Python标准库中的sqlite3模块提供了一个轻量级的接口来执行SQL命令。
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和连接
cursor.close()
conn.close()
第三方库: 对于其他类型的数据库,如MySQL、PostgreSQL、MongoDB等,通常需要安装相应的第三方库。
MySQL:可以使用mysql-connector-python或PyMySQL。
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
PostgreSQL:可以使用psycopg2。
import psycopg2
conn = psycopg2.connect(
dbname="mydatabase",
user="username",
password="password",
host="127.0.0.1",
port="5432"
)
cur = conn.cursor()
cur.execute("SELECT * FROM employees")
rows = cur.fetchall()
for row in rows:
print(row)
MongoDB:可以使用pymongo。
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["customers"]
mydict = { "name": "John", "address": "Highway 37" }
x = collection.insert_one(mydict)
print(x.inserted_id)
ORM(对象关系映射)工具: ORM工具允许你使用Python类和对象来操作数据库,而不是直接编写SQL语句。这样可以提高代码的可读性和可维护性。
SQLAlchemy:是一个流行的Python SQL工具包和对象关系映射(ORM)系统。
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)
name = Column(String)
fullname = Column(String)
nickname = Column(String)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
ed_user = User(name='ed', fullname='Ed Jones', nickname='ednick')
session.add(ed_user)
session.commit()
Django ORM:如果你在使用Django框架,它自带了一个强大的ORM。
from django.db import models
class MyModel(models.Model):
my_field = models.CharField(max_length=100)
# 创建新对象
obj = MyModel(my_field='Hello, world!')
obj.save()
# 查询数据库
for obj in MyModel.objects.all():
print(obj.my_field)
选择哪种方法取决于你的具体需求、数据库类型以及个人偏好。对于简单的任务,使用Python标准库可能就足够了。而对于更复杂的应用,使用ORM工具可能会更加方便。