centos

CentOS Python数据库如何连接

小樊
47
2025-09-18 02:17:05
栏目: 编程语言

在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成功连接到所需的数据库。

0
看了该问题的人还看了