ubuntu

ubuntu里python如何连接数据库

小樊
43
2025-05-18 00:06:17
栏目: 编程语言

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

1. MySQL

使用mysql-connector-pythonPyMySQL库。

安装库

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

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

import mysql.connector

# 连接到数据库
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# 创建游标
mycursor = mydb.cursor()

# 执行SQL查询
mycursor.execute("SELECT * FROM yourtable")

# 获取所有记录
myresult = mycursor.fetchall()

for x in myresult:
  print(x)

2. PostgreSQL

使用psycopg2库。

安装库

pip install psycopg2
# 或者
pip install psycopg2-binary

示例代码

import psycopg2

# 连接到数据库
conn = psycopg2.connect(
    dbname="yourdatabase",
    user="yourusername",
    password="yourpassword",
    host="localhost"
)

# 创建游标
cur = conn.cursor()

# 执行SQL查询
cur.execute("SELECT * FROM yourtable")

# 获取所有记录
rows = cur.fetchall()

for row in rows:
    print(row)

3. SQLite

使用内置的sqlite3模块。

示例代码

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('yourdatabase.db')

# 创建游标
cursor = conn.cursor()

# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")

# 获取所有记录
rows = cursor.fetchall()

for row in rows:
    print(row)

4. MongoDB

使用pymongo库。

安装库

pip install pymongo

示例代码

from pymongo import MongoClient

# 连接到MongoDB服务器
client = MongoClient('mongodb://localhost:27017/')

# 选择数据库
db = client['yourdatabase']

# 选择集合
collection = db['yourcollection']

# 查询文档
documents = collection.find()

for doc in documents:
    print(doc)

5. Redis

使用redis-py库。

安装库

pip install redis

示例代码

import redis

# 连接到Redis服务器
r = redis.Redis(host='localhost', port=6379, db=0)

# 设置键值对
r.set('key', 'value')

# 获取键值对
value = r.get('key')
print(value)

注意事项

  1. 安全性:避免在代码中硬编码数据库凭据,可以使用环境变量或配置文件来存储敏感信息。
  2. 错误处理:在实际应用中,应该添加适当的错误处理机制,以应对数据库连接失败或其他异常情况。
  3. 依赖管理:使用虚拟环境(如venvconda)来管理项目的依赖关系,避免全局安装的库版本冲突。

通过以上方法,你可以在Ubuntu系统中使用Python连接到各种数据库并进行操作。

0
看了该问题的人还看了