在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")
根据需要选择合适的数据库驱动和库,并按照上述示例设置连接参数。在实际应用中,可能需要根据业务需求编写相应的数据库操作代码。