在CentOS中,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的Python库,以及如何使用它们连接到数据库的示例。
对于MySQL数据库,可以使用mysql-connector-python库。
安装库:
pip install mysql-connector-python
连接示例:
import mysql.connector
# 连接到MySQL数据库
cnx = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database"
)
# 创建游标对象
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取查询结果
for row in cursor.fetchall():
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
对于PostgreSQL数据库,可以使用psycopg2库。
安装库:
pip install psycopg2-binary
连接示例:
import psycopg2
# 连接到PostgreSQL数据库
conn = psycopg2.connect(
dbname="your_database",
user="your_user",
password="your_password",
host="your_host",
port="your_port"
)
# 创建游标对象
cur = conn.cursor()
# 执行SQL查询
cur.execute("SELECT * FROM your_table")
# 获取查询结果
rows = cur.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cur.close()
conn.close()
对于SQLite数据库,可以使用Python内置的sqlite3库。
连接示例:
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('your_database.db')
# 创建游标对象
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取查询结果
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
对于MongoDB数据库,可以使用pymongo库。
安装库:
pip install pymongo
连接示例:
from pymongo import MongoClient
# 连接到MongoDB数据库
client = MongoClient("mongodb://your_host:your_port")
# 选择数据库
db = client["your_database"]
# 选择集合
collection = db["your_collection"]
# 查询文档
documents = collection.find()
for document in documents:
print(document)
请根据您的需求选择合适的库,并确保已正确安装所需的依赖项。在连接到数据库时,请确保使用正确的凭据和连接参数。