在CentOS系统下配置Python数据库连接,通常需要以下几个步骤:
sudo yum install mysql-server
sudo systemctl start mysqld
sudo systemctl enable mysqld
运行mysql_secure_installation
命令来设置MySQL的安全选项,如设置密码、删除匿名用户等。
pip
安装mysql-connector-python
库:pip install mysql-connector-python
对于PostgreSQL,你可以安装psycopg2
库:
pip install psycopg2
db_connection.py
),并编写代码来连接数据库。以下是一个使用MySQL的示例:import mysql.connector
# 创建数据库连接
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# 创建游标对象
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取查询结果
for row in cursor.fetchall():
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
将上述代码中的your_username
、your_password
、your_database
和your_table
替换为实际的值。
在终端中运行你的Python脚本,如:
python db_connection.py
这样,你就可以在CentOS系统下使用Python连接数据库了。如果你使用的是其他类型的数据库,请安装相应的Python库,并根据库的文档编写连接代码。