在CentOS上使用Python连接数据库,通常需要使用数据库的官方Python驱动程序。以下是一些常见数据库及其对应的Python连接方法:
安装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)
安装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)
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()
安装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连接到不同的数据库。