在CentOS上,Python可以通过多种方式连接到数据库。以下是一些常见的数据库连接方法:
mysql-connector-python
连接MySQL数据库首先,安装mysql-connector-python
库:
pip install mysql-connector-python
然后,使用以下代码连接到MySQL数据库:
import mysql.connector
# 创建数据库连接
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:
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
psycopg2
连接PostgreSQL数据库首先,安装psycopg2
库:
pip install psycopg2
然后,使用以下代码连接到PostgreSQL数据库:
import psycopg2
# 创建数据库连接
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()
sqlite3
连接SQLite数据库Python标准库中包含了sqlite3
模块,无需额外安装。使用以下代码连接到SQLite数据库:
import sqlite3
# 创建数据库连接
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()
pymongo
连接MongoDB数据库首先,安装pymongo
库:
pip install pymongo
然后,使用以下代码连接到MongoDB数据库:
from pymongo import MongoClient
# 创建MongoDB客户端
client = MongoClient('mongodb://your_host:your_port')
# 选择数据库
db = client['your_database']
# 选择集合
collection = db['your_collection']
# 查询文档
documents = collection.find()
for doc in documents:
print(doc)
通过以上方法,你可以在CentOS上使用Python连接到不同的数据库。