在CentOS上,Python可以通过多种方式连接到数据库。以下是一些常见的数据库连接方法:
1. 使用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()
2. 使用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()
3. 使用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()
4. 使用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连接到不同的数据库。