在CentOS中配置Python数据库连接,通常涉及以下几个步骤:
安装Python: 如果你还没有安装Python,可以使用以下命令安装:
sudo yum install python3
安装数据库驱动:
根据你要连接的数据库类型,安装相应的Python驱动。例如,如果你要连接MySQL数据库,可以安装mysql-connector-python
或PyMySQL
:
sudo yum install mysql-connector-python
或者
sudo yum install python3-PyMySQL
编写Python脚本:
创建一个Python脚本来测试数据库连接。以下是一个使用mysql-connector-python
连接MySQL数据库的示例:
import mysql.connector
# 数据库配置
config = {
'user': 'your_username',
'password': 'your_password',
'host': '127.0.0.1',
'database': 'your_database',
'raise_on_warnings': True
}
try:
# 建立数据库连接
cnx = mysql.connector.connect(**config)
print("Connected to MySQL database")
# 创建游标对象
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取查询结果
for row in cursor:
print(row)
except mysql.connector.Error as e:
print(f"Error: {e}")
finally:
# 关闭游标和连接
if cursor:
cursor.close()
if cnx:
cnx.close()
print("MySQL connection is closed")
运行Python脚本:
保存上述脚本到一个文件(例如test_db_connection.py
),然后在终端中运行:
python3 test_db_connection.py
sudo systemctl start mysqld
通过以上步骤,你应该能够在CentOS中成功配置Python数据库连接。