要在Python中连接到CentOS上的数据库,首先需要确保已经安装了相应的数据库服务(如MySQL、PostgreSQL等)以及Python的数据库驱动程序。以下是连接到CentOS上的MySQL和PostgreSQL数据库的示例。
连接到MySQL数据库
sudo yum install mysql-server
sudo systemctl start mysqld
sudo systemctl enable mysqld
mysql-connector-python
):pip install mysql-connector-python
import mysql.connector
# 替换以下信息
user = "your_username"
password = "your_password"
host = "your_host" # 通常是 "localhost" 或服务器的IP地址
database = "your_database"
# 建立连接
connection = mysql.connector.connect(
user=user,
password=password,
host=host,
database=database
)
# 使用连接进行操作
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table")
result = cursor.fetchall()
for row in result:
print(row)
# 关闭连接
cursor.close()
connection.close()
连接到PostgreSQL数据库
sudo yum install postgresql-server
sudo systemctl start postgresql
sudo systemctl enable postgresql
sudo passwd postgres
sudo -u postgres psql
在psql命令行中执行以下SQL命令:
CREATE USER your_username WITH PASSWORD 'your_password';
CREATE DATABASE your_database;
GRANT ALL PRIVILEGES ON DATABASE your_database TO your_username;
\q
psycopg2
):pip install psycopg2
import psycopg2
# 替换以下信息
user = "your_username"
password = "your_password"
host = "your_host" # 通常是 "localhost" 或服务器的IP地址
database = "your_database"
# 建立连接
connection = psycopg2.connect(
user=user,
password=password,
host=host,
database=database
)
# 使用连接进行操作
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table")
result = cursor.fetchall()
for row in result:
print(row)
# 关闭连接
cursor.close()
connection.close()
请根据实际情况替换上述示例中的用户名、密码、主机和数据库名称。