在CentOS系統下,使用Python連接數據庫通常需要安裝相應的數據庫驅動和庫。以下是一些常見數據庫的連接設置方法:
首先,確保已經安裝了MySQL數據庫。然后,使用pip安裝MySQL Connector/Python庫:
pip install mysql-connector-python
接下來,創建一個Python腳本并導入所需的庫:
import mysql.connector
from mysql.connector import Error
設置數據庫連接參數:
try:
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
if connection.is_connected():
print("Connected to MySQL database")
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
connection.close()
print("MySQL connection is closed")
首先,確保已經安裝了PostgreSQL數據庫。然后,使用pip安裝psycopg2庫:
pip install psycopg2
接下來,創建一個Python腳本并導入所需的庫:
import psycopg2
from psycopg2 import OperationalError
設置數據庫連接參數:
try:
connection = psycopg2.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
if connection:
print("Connected to PostgreSQL database")
except OperationalError as e:
print("Error while connecting to PostgreSQL", e)
finally:
if connection:
connection.close()
print("PostgreSQL connection is closed")
SQLite是一個輕量級的數據庫,不需要單獨安裝。使用Python內置的sqlite3庫進行連接:
import sqlite3
設置數據庫連接參數:
try:
connection = sqlite3.connect('your_database.db')
if connection:
print("Connected to SQLite database")
except sqlite3.Error as e:
print("Error while connecting to SQLite", e)
finally:
if connection:
connection.close()
print("SQLite connection is closed")
根據需要選擇合適的數據庫驅動和庫,并按照上述示例設置連接參數。在實際應用中,可能需要根據業務需求編寫相應的數據庫操作代碼。