溫馨提示×

Python在Debian上的數據庫連接方法

小樊
51
2025-04-30 07:44:00
欄目: 編程語言

在Debian上使用Python連接數據庫,通常需要安裝相應的數據庫驅動和庫。以下是一些常見數據庫的連接方法:

  1. MySQL/MariaDB:

首先,安裝python3-mysqldbpython3-pymysql庫。

sudo apt-get install python3-mysqldb
# 或者
sudo apt-get install python3-pymysql

然后,在Python代碼中使用相應的庫連接數據庫:

import pymysql

# 使用 pymysql 連接
conn = pymysql.connect(host='localhost', user='your_user', password='your_password', db='your_database')
cursor = conn.cursor()

# 執行 SQL 查詢
cursor.execute('SELECT * FROM your_table')

# 獲取查詢結果
results = cursor.fetchall()

# 關閉連接
cursor.close()
conn.close()
  1. PostgreSQL:

首先,安裝python3-psycopg2庫。

sudo apt-get install python3-psycopg2

然后,在Python代碼中使用該庫連接數據庫:

import psycopg2

# 使用 psycopg2 連接
conn = psycopg2.connect(host='localhost', user='your_user', password='your_password', dbname='your_database')
cursor = conn.cursor()

# 執行 SQL 查詢
cursor.execute('SELECT * FROM your_table')

# 獲取查詢結果
results = cursor.fetchall()

# 關閉連接
cursor.close()
conn.close()
  1. SQLite:

SQLite是一個輕量級的數據庫,不需要額外安裝庫。直接在Python中使用內置的sqlite3模塊連接數據庫:

import sqlite3

# 使用 sqlite3 連接
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()

# 執行 SQL 查詢
cursor.execute('SELECT * FROM your_table')

# 獲取查詢結果
results = cursor.fetchall()

# 關閉連接
cursor.close()
conn.close()
  1. MongoDB:

首先,安裝pymongo庫。

pip3 install pymongo

然后,在Python代碼中使用該庫連接數據庫:

from pymongo import MongoClient

# 使用 MongoClient 連接
client = MongoClient('mongodb://your_user:your_password@localhost:27017/your_database')

# 選擇數據庫和集合
db = client['your_database']
collection = db['your_table']

# 查詢文檔
documents = collection.find()

# 遍歷查詢結果
for document in documents:
    print(document)

# 關閉連接
client.close()

根據需要選擇合適的數據庫和連接方法。注意替換示例代碼中的your_user、your_password、your_databaseyour_table為實際的值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女