在Ubuntu系统中,Python与数据库交互通常是通过使用数据库驱动程序和Python的数据库API来实现的。以下是一些常见的数据库及其对应的Python驱动程序和基本操作步骤:
安装MySQL驱动程序:
pip install mysql-connector-python
示例代码:
import mysql.connector
# 连接到数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
# 执行SQL查询
mycursor.execute("SELECT * FROM yourtable")
# 获取查询结果
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# 关闭连接
mydb.close()
安装PostgreSQL驱动程序:
pip install psycopg2-binary
示例代码:
import psycopg2
# 连接到数据库
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
# 创建游标对象
cur = conn.cursor()
# 执行SQL查询
cur.execute("SELECT * FROM yourtable")
# 获取查询结果
rows = cur.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cur.close()
conn.close()
安装SQLite驱动程序:
pip install pysqlite3
示例代码:
import sqlite3
# 连接到数据库
conn = sqlite3.connect('yourdatabase.db')
# 创建游标对象
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")
# 获取查询结果
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
安装MongoDB驱动程序:
pip install pymongo
示例代码:
from pymongo import MongoClient
# 连接到MongoDB服务器
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['yourdatabase']
# 选择集合
collection = db['yourcollection']
# 插入文档
document = {"name": "John", "age": 30}
collection.insert_one(document)
# 查询文档
for doc in collection.find():
print(doc)
# 关闭连接
client.close()
通过以上步骤,你可以在Ubuntu系统中使用Python与各种数据库进行交互。