在Debian系统下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库及其对应的Python连接方法:
使用mysql-connector-python
或PyMySQL
库来连接MySQL或MariaDB数据库。
安装库:
pip install mysql-connector-python
# 或者
pip install pymysql
示例代码 (使用mysql-connector-python
):
import mysql.connector
cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='mydb')
cursor = cnx.cursor()
query = "SELECT * FROM mytable"
cursor.execute(query)
for row in cursor:
print(row)
cursor.close()
cnx.close()
使用psycopg2
库来连接PostgreSQL数据库。
安装库:
pip install psycopg2
# 或者
pip install psycopg2-binary
示例代码:
import psycopg2
conn = psycopg2.connect(user='username', password='password', host='localhost', dbname='mydb')
cur = conn.cursor()
cur.execute("SELECT * FROM mytable")
rows = cur.fetchall()
for row in rows:
print(row)
cur.close()
conn.close()
Python内置了对SQLite的支持,无需安装额外的库。
示例代码:
import sqlite3
conn = sqlite3.connect('mydb.sqlite3')
cursor = conn.cursor()
cursor.execute("SELECT * FROM mytable")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.close()
conn.close()
使用pymongo
库来连接MongoDB数据库。
安装库:
pip install pymongo
示例代码:
from pymongo import MongoClient
client = MongoClient('mongodb://username:password@localhost:27017/mydb')
db = client['mydb']
collection = db['mytable']
documents = collection.find()
for doc in documents:
print(doc)
请根据您使用的数据库类型选择合适的库,并按照示例代码进行操作。注意替换示例代码中的username
、password
、host
、database
和mytable
等参数为您自己的数据库信息。