阅读量:2
在CentOS上使用Python连接数据库,通常会使用到一些流行的数据库驱动程序。以下是一些常见数据库及其对应的Python连接方法:
1. MySQL/MariaDB
安装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()
mycursor.execute("SELECT * FROM customers")
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 customers
(id integer PRIMARY KEY, name text, address text)''')
cursor.execute("INSERT INTO customers (name, address) VALUES ('John Doe', '123 Main St')")
conn.commit()
cursor.execute("SELECT * FROM customers")
rows = cursor.fetchall()
for row in rows:
print(row)
conn.close()
4. MongoDB
安装MongoDB客户端库:
sudo yum install mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod
安装Python的MongoDB驱动:
pip install pymongo
示例代码:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['yourdatabase']
collection = db['customers']
# 插入文档
collection.insert_one({"name": "John Doe", "address": "123 Main St"})
# 查询文档
for document in collection.find():
print(document)
注意事项:
- 确保数据库服务正在运行。
- 根据实际情况修改连接参数(如主机名、端口、用户名、密码和数据库名称)。
- 在生产环境中,建议使用环境变量或配置文件来管理敏感信息。
通过以上步骤,你应该能够在CentOS上使用Python成功连接到所需的数据库。
以上就是关于“CentOS Python数据库如何连接”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm