Ubuntu中Python与数据库交互如何操作

作者:袖梨 2026-07-03

在Ubuntu系统中,Python与数据库交互通常是通过使用数据库驱动程序和Python的数据库API来实现的。以下是一些常见的数据库及其对应的Python驱动程序和基本操作步骤:

Ubuntu中Python与数据库交互怎么操作

1. MySQL

安装MySQL驱动程序:

pip install 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)# 关闭连接mydb.close()

2. PostgreSQL

安装PostgreSQL驱动程序:

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)# 关闭游标和连接cur.close()conn.close()

3. SQLite

安装SQLite驱动程序:

pip install pysqlite3

示例代码:

import sqlite3# 连接到数据库conn = sqlite3.connect('yourdatabase.db')# 创建游标对象cursor = conn.cursor()# 执行SQL查询cursor.execute("SELECT * FROM yourtable")# 获取查询结果rows = cursor.fetchall()for row in rows:print(row)# 关闭游标和连接cursor.close()conn.close()

4. MongoDB

安装MongoDB驱动程序:

pip install pymongo

示例代码:

from pymongo import MongoClient# 连接到MongoDB服务器client = MongoClient('mongodb://localhost:27017/')# 选择数据库db = client['yourdatabase']# 选择集合collection = db['yourcollection']# 插入文档document = {"name": "John", "age": 30}collection.insert_one(document)# 查询文档for doc in collection.find():print(doc)# 关闭连接client.close()

注意事项:

  1. 安全性:在实际应用中,不要在代码中硬编码数据库凭据,可以使用环境变量或配置文件来管理。
  2. 异常处理:在执行数据库操作时,应该添加异常处理机制,以便在发生错误时能够捕获并处理。
  3. 资源管理:确保在操作完成后关闭数据库连接和游标,以释放资源。

通过以上步骤,你可以在Ubuntu系统中使用Python与各种数据库进行交互。

相关文章

精彩推荐