在Linux系统中,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的Python库:
MySQL/MariaDB:
使用mysql-connector-python或PyMySQL库。
安装: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='mydatabase')
cursor = cnx.cursor()
query = ("SELECT * FROM mytable")
cursor.execute(query)
for row in cursor:
print(row)
cursor.close()
cnx.close()
PostgreSQL:
使用psycopg2库。
安装:pip install psycopg2 或 pip install psycopg2-binary
示例代码:
import psycopg2
conn = psycopg2.connect(dbname="mydatabase", user="username",
password="password", host="localhost")
cur = conn.cursor()
cur.execute("SELECT * FROM mytable;")
rows = cur.fetchall()
for row in rows:
print(row)
cur.close()
conn.close()
SQLite:
使用sqlite3库,它是Python标准库的一部分。
示例代码:
import sqlite3
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM mytable")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.close()
conn.close()
MongoDB:
使用pymongo库。
安装:pip install pymongo
示例代码:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
collection = db['mytable']
for document in collection.find():
print(document)
Redis:
使用redis-py库。
安装:pip install redis
示例代码:
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('mykey', 'Hello, Redis!')
value = r.get('mykey')
print(value)
根据您使用的数据库类型,选择一个合适的库并按照示例代码进行操作。注意替换示例代码中的数据库连接信息(如用户名、密码、主机名和数据库名)以满足您的实际需求。