在CentOS系统下,使用Python连接数据库通常需要安装相应的数据库驱动和库。以下是一些常见数据库的连接方法:
首先,安装MySQL数据库驱动mysql-connector-python
:
pip install mysql-connector-python
然后,使用以下代码连接到MySQL数据库:
import mysql.connector
cnx = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database"
)
cursor = cnx.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取查询结果
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
首先,安装PostgreSQL数据库驱动psycopg2
:
pip install psycopg2
然后,使用以下代码连接到PostgreSQL数据库:
import psycopg2
conn = psycopg2.connect(
dbname="your_database",
user="your_user",
password="your_password",
host="your_host",
port="your_port"
)
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取查询结果
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
首先,导入SQLite数据库库sqlite3
:
import sqlite3
然后,使用以下代码连接到SQLite数据库:
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取查询结果
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
根据需要选择合适的数据库驱动和库,并按照相应的示例代码进行连接。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: CentOS FTPS服务器的性能如何优化