阅读量:2
在CentOS上使用Python连接数据库,通常需要使用数据库的官方Python驱动程序。以下是一些常见数据库及其对应的Python连接方法:
1. MySQL
安装MySQL客户端库:
sudo yum install mysql-devel
安装Python的MySQL驱动:
pip install mysql-connector-python
示例代码:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
2. PostgreSQL
安装PostgreSQL客户端库:
sudo yum install postgresql-devel
安装Python的PostgreSQL驱动:
pip install psycopg2-binary
示例代码:
import psycopg2
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
cur = conn.cursor()
cur.execute("SELECT * FROM customers")
rows = cur.fetchall()
for row in rows:
print(row)
3. SQLite
SQLite是一个嵌入式数据库,不需要单独安装客户端库。
安装Python的SQLite驱动(通常已经内置):
pip install pysqlite3
示例代码:
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
(date text, trans text, symbol text, qty real, price real)''')
cursor.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
conn.commit()
cursor.execute("SELECT * FROM stocks")
for row in cursor.fetchall():
print(row)
conn.close()
4. MongoDB
安装MongoDB客户端库:
sudo yum install mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
pip install pymongo
示例代码:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['yourdatabase']
collection = db['customers']
# 插入文档
post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]}
post_id = collection.insert_one(post).inserted_id
# 查询文档
for post in collection.find():
print(post)
注意事项
- 权限和安全性:确保数据库用户有适当的权限,并且密码安全。
- 网络配置:如果数据库不在本地,确保防火墙允许相应的端口通信。
- 依赖管理:使用虚拟环境(如
virtualenv或conda)来管理项目依赖,避免全局安装导致的冲突。
通过以上步骤,你可以在CentOS上使用Python连接到不同的数据库。
以上就是关于“CentOS Python如何连接数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm