debian

Debian下Python与数据库如何连接

小樊
40
2025-08-28 06:01:28
栏目: 编程语言

在Debian系统下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库及其对应的Python连接方法:

  1. MySQL/MariaDB:

使用mysql-connector-pythonPyMySQL库来连接MySQL或MariaDB数据库。

安装库:

pip install mysql-connector-python
# 或者
pip install pymysql

示例代码 (使用mysql-connector-python):

import mysql.connector

cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='mydb')
cursor = cnx.cursor()

query = "SELECT * FROM mytable"
cursor.execute(query)

for row in cursor:
    print(row)

cursor.close()
cnx.close()
  1. PostgreSQL:

使用psycopg2库来连接PostgreSQL数据库。

安装库:

pip install psycopg2
# 或者
pip install psycopg2-binary

示例代码:

import psycopg2

conn = psycopg2.connect(user='username', password='password', host='localhost', dbname='mydb')
cur = conn.cursor()

cur.execute("SELECT * FROM mytable")
rows = cur.fetchall()

for row in rows:
    print(row)

cur.close()
conn.close()
  1. SQLite:

Python内置了对SQLite的支持,无需安装额外的库。

示例代码:

import sqlite3

conn = sqlite3.connect('mydb.sqlite3')
cursor = conn.cursor()

cursor.execute("SELECT * FROM mytable")
rows = cursor.fetchall()

for row in rows:
    print(row)

cursor.close()
conn.close()
  1. MongoDB:

使用pymongo库来连接MongoDB数据库。

安装库:

pip install pymongo

示例代码:

from pymongo import MongoClient

client = MongoClient('mongodb://username:password@localhost:27017/mydb')

db = client['mydb']
collection = db['mytable']

documents = collection.find()

for doc in documents:
    print(doc)

请根据您使用的数据库类型选择合适的库,并按照示例代码进行操作。注意替换示例代码中的usernamepasswordhostdatabasemytable等参数为您自己的数据库信息。

0
看了该问题的人还看了