在Ubuntu系统中,Python可以通过多种方式连接到数据库。以下是一些常见的数据库及其对应的Python连接方法:
使用mysql-connector-python
或PyMySQL
库。
pip install mysql-connector-python
# 或者
pip install PyMySQL
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)
使用psycopg2
库。
pip install psycopg2
# 或者
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)
使用内置的sqlite3
模块。
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('yourdatabase.db')
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")
# 获取所有记录
rows = cursor.fetchall()
for row in rows:
print(row)
使用pymongo
库。
pip install pymongo
from pymongo import MongoClient
# 连接到MongoDB服务器
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['yourdatabase']
# 选择集合
collection = db['yourcollection']
# 查询文档
documents = collection.find()
for doc in documents:
print(doc)
使用redis-py
库。
pip install redis
import redis
# 连接到Redis服务器
r = redis.Redis(host='localhost', port=6379, db=0)
# 设置键值对
r.set('key', 'value')
# 获取键值对
value = r.get('key')
print(value)
venv
或conda
)来管理项目的依赖关系,避免全局安装的库版本冲突。通过以上方法,你可以在Ubuntu系统中使用Python连接到各种数据库并进行操作。