centos

Python与CentOS数据库如何连接

小樊
44
2025-09-18 02:08:05
栏目: 编程语言

要在Python中连接到CentOS上的数据库,首先需要确保已经安装了相应的数据库服务(如MySQL、PostgreSQL等)以及Python的数据库驱动程序。以下是连接到CentOS上的MySQL和PostgreSQL数据库的示例。

连接到MySQL数据库

  1. 安装MySQL服务(如果尚未安装):
sudo yum install mysql-server
sudo systemctl start mysqld
sudo systemctl enable mysqld
  1. 安装Python的MySQL驱动程序(如mysql-connector-python):
pip install mysql-connector-python
  1. 使用Python连接到MySQL数据库:
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数据库

  1. 安装PostgreSQL服务(如果尚未安装):
sudo yum install postgresql-server
sudo systemctl start postgresql
sudo systemctl enable postgresql
  1. 创建一个新用户并授权访问数据库(可选):
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
  1. 安装Python的PostgreSQL驱动程序(如psycopg2):
pip install psycopg2
  1. 使用Python连接到PostgreSQL数据库:
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()

请根据实际情况替换上述示例中的用户名、密码、主机和数据库名称。

0
看了该问题的人还看了