阅读量:3
要在Python中连接到CentOS上的数据库,首先需要确保已经安装了相应的数据库服务(如MySQL、PostgreSQL等)以及Python的数据库驱动程序。以下是连接到CentOS上的MySQL和PostgreSQL数据库的示例。
连接到MySQL数据库
- 安装MySQL服务(如果尚未安装):
sudo yum install mysql-server
sudo systemctl start mysqld
sudo systemctl enable mysqld
- 安装Python的MySQL驱动程序(如
mysql-connector-python):
pip install mysql-connector-python
- 使用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数据库
- 安装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
- 安装Python的PostgreSQL驱动程序(如
psycopg2):
pip install psycopg2
- 使用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()
请根据实际情况替换上述示例中的用户名、密码、主机和数据库名称。
以上就是关于“Python与CentOS数据库如何连接”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm