在CentOS系统下,Python可以通过多种方式与数据库进行连接。以下是一些常见的数据库及其对应的Python连接方法:
使用mysql-connector-python或PyMySQL库。
pip install mysql-connector-python
# 或者
pip install PyMySQL
mysql-connector-python)import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标
mycursor = mydb.cursor()
# 执行SQL查询
mycursor.execute("SELECT * FROM yourtable")
# 获取所有记录
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# 关闭连接
mydb.close()
使用psycopg2库。
pip install psycopg2
# 或者
pip install psycopg2-binary
import psycopg2
# 连接数据库
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
# 创建游标
cur = conn.cursor()
# 执行SQL查询
cur.execute("SELECT * FROM yourtable")
# 获取所有记录
rows = cur.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cur.close()
conn.close()
使用sqlite3库,这是Python标准库的一部分。
import sqlite3
# 连接数据库
conn = sqlite3.connect('yourdatabase.db')
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")
# 获取所有记录
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
使用pymongo库。
pip install pymongo
from pymongo import MongoClient
# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['yourdatabase']
# 选择集合
collection = db['yourcollection']
# 查询所有文档
documents = collection.find()
for doc in documents:
print(doc)
使用cx_Oracle库。
pip install cx_Oracle
import cx_Oracle
# 连接数据库
dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='your_service_name')
conn = cx_Oracle.connect(user='yourusername', password='yourpassword', dsn=dsn_tns)
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")
# 获取所有记录
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
通过以上方法,你可以在CentOS系统下使用Python与各种数据库进行连接和操作。