在Debian系统下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库及其对应的Python连接方法:
使用mysql-connector-python库:
pip install mysql-connector-python
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
Python代码示例:
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库(Python标准库自带):
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)
使用pymongo库:
pip install pymongo
Python代码示例:
from pymongo import MongoClient
# 连接到MongoDB
client = MongoClient("mongodb://localhost:27017/")
# 选择数据库
db = client["yourdatabase"]
# 选择集合
collection = db["yourcollection"]
# 查询文档
documents = collection.find()
for document in documents:
print(document)
使用redis-py库:
pip install redis
Python代码示例:
import redis
# 连接到Redis
r = redis.Redis(host='localhost', port=6379, db=0)
# 设置键值对
r.set('yourkey', 'yourvalue')
# 获取键值对
value = r.get('yourkey')
print(value)
通过以上方法,你可以在Debian系统下使用Python连接到各种数据库。