centos

Python在CentOS中的数据库连接方法

小樊
43
2025-09-20 09:05:40
栏目: 编程语言

在CentOS系统中,使用Python连接数据库有多种方法,具体取决于你使用的数据库类型。以下是一些常见的数据库及其在CentOS上的Python连接方法:

1. MySQL

对于MySQL数据库,可以使用mysql-connector-pythonPyMySQL库。

安装依赖

sudo yum install python3-devel mysql-devel

使用mysql-connector-python

pip3 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)

使用PyMySQL

pip3 install PyMySQL

示例代码

import pymysql

conn = pymysql.connect(host='localhost', user='yourusername', password='yourpassword', db='yourdatabase')

cursor = conn.cursor()

sql = "SELECT * FROM customers"
cursor.execute(sql)

result = cursor.fetchall()

for row in result:
    print(row)

conn.close()

2. PostgreSQL

对于PostgreSQL数据库,可以使用psycopg2库。

安装依赖

sudo yum install postgresql-devel python3-devel

安装psycopg2

pip3 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)

conn.close()

3. SQLite

对于SQLite数据库,可以使用内置的sqlite3模块。

示例代码

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数据库,可以使用pymongo库。

安装依赖

sudo yum install python3-devel

安装pymongo

pip3 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 doc in collection.find():
    print(doc)

总结

选择合适的库并安装相应的依赖后,你可以使用Python连接到不同的数据库,并执行查询、插入、更新等操作。确保在编写代码时处理异常和关闭数据库连接,以避免资源泄漏。

0
看了该问题的人还看了