在Ubuntu系统中,Python可以通过多种方式与数据库进行交互。以下是一些常见的数据库和相应的Python库,以及如何使用它们进行交互的简要说明:
SQLite: SQLite是一个轻量级的数据库,它内置于Python标准库中,因此不需要安装额外的包。
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()
MySQL:
对于MySQL数据库,可以使用mysql-connector-python
或pymysql
库。
pip install mysql-connector-python
或者
pip install pymysql
使用mysql-connector-python
:
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 * FROM employees WHERE department = %s")
cursor.execute(query, ('Sales',))
# 获取查询结果
for (employee, department) in cursor:
print(f"{employee} works in the {department} department")
# 关闭Cursor和连接
cursor.close()
cnx.close()
PostgreSQL:
对于PostgreSQL数据库,可以使用psycopg2
库。
pip install psycopg2
或者
pip install psycopg2-binary
使用psycopg2
:
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 * FROM employees")
# 获取查询结果
records = cursor.fetchall()
for record in records:
print(record)
# 关闭Cursor和连接
cursor.close()
conn.close()
MongoDB:
对于MongoDB数据库,可以使用pymongo
库。
pip install pymongo
使用pymongo
:
from pymongo import MongoClient
# 连接到MongoDB
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['mydatabase']
# 选择集合
collection = db['employees']
# 插入文档
post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]}
post_id = collection.insert_one(post).inserted_id
# 查询文档
for post in collection.find():
print(post)
在使用这些库时,请确保遵循最佳实践,例如使用参数化查询来防止SQL注入攻击,并在完成数据库操作后适当地关闭连接。