在CentOS上配置Python連接數據庫通常涉及以下幾個步驟:
pymysql
用于MySQL,psycopg2
用于PostgreSQL。使用pip
安裝所需的Python庫。例如,安裝pymysql
或psycopg2
:
pip install pymysql
# 或者
pip install psycopg2-binary
pymysql
):import pymysql
# 創建連接對象
connection = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
# 創建游標對象
cursor = connection.cursor()
# 執行SQL查詢
cursor.execute('SELECT * FROM your_table')
# 獲取查詢結果
results = cursor.fetchall()
# 打印結果
for row in results:
print(row)
# 關閉游標和連接
cursor.close()
connection.close()
psycopg2
):import psycopg2
# 創建連接對象
connection = psycopg2.connect(
dbname='your_database',
user='your_username',
password='your_password',
host='your_host',
port='your_port'
)
# 創建游標對象
cursor = connection.cursor()
# 執行SQL查詢
cursor.execute('SELECT version()')
# 獲取查詢結果
db_version = cursor.fetchone()
print(f"Database version: {db_version}")
# 關閉游標和連接
cursor.close()
connection.close()
為了提高安全性和管理便利性,可以將數據庫連接參數存儲在配置文件中,如database.ini
:
[postgresql]
host = your_host
database = your_database
user = your_username
password = your_password
port = your_port
然后在Python代碼中使用configparser
模塊讀取配置文件:
import psycopg2
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
parser = ConfigParser()
parser.read(filename)
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception(f'Section {section} not found in the {filename} file')
return db
# 使用配置文件中的參數連接數據庫
conn = psycopg2.connect(**config())
在實際應用中,應該使用try...except
塊來捕獲和處理可能的異常,如連接失敗或執行SQL語句錯誤。此外,使用事務管理可以確保數據的一致性和完整性。
以上步驟展示了如何在CentOS上使用Python連接到MySQL和PostgreSQL數據庫。根據具體的數據庫類型和需求,可能需要調整連接庫和連接參數。