温馨提示×

Python在Debian上的数据库连接方法

小樊
52
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_useryour_passwordyour_databaseyour_table为实际的值。

0