温馨提示×

Python在Ubuntu上如何进行数据库连接

小樊
46
2025-10-16 08:47:59
栏目: 编程语言

在Ubuntu上使用Python连接数据库,通常需要安装相应的数据库驱动和库。以下是一些常见数据库的连接方法:

1. 连接MySQL数据库

安装MySQL客户端库

sudo apt update sudo apt install python3-mysqldb 

Python代码示例

import MySQLdb # 连接数据库 conn = MySQLdb.connect( host="localhost", user="your_username", passwd="your_password", db="your_database" ) # 创建游标 cursor = conn.cursor() # 执行SQL查询 cursor.execute("SELECT VERSION()") # 获取单条数据 data = cursor.fetchone() print("Database version : %s " % data) # 关闭连接 conn.close() 

2. 连接PostgreSQL数据库

安装PostgreSQL客户端库

sudo apt update sudo apt install python3-psycopg2 

Python代码示例

import psycopg2 # 连接数据库 conn = psycopg2.connect( dbname="your_database", user="your_username", password="your_password", host="localhost", port="5432" ) # 创建游标 cursor = conn.cursor() # 执行SQL查询 cursor.execute("SELECT version();") # 获取单条数据 db_version = cursor.fetchone() print("Database version : %s " % db_version) # 关闭连接 conn.close() 

3. 连接SQLite数据库

SQLite是一个嵌入式数据库,不需要额外的客户端库。

Python代码示例

import sqlite3 # 连接数据库 conn = sqlite3.connect('your_database.db') # 创建游标 cursor = conn.cursor() # 执行SQL查询 cursor.execute("SELECT sqlite_version();") # 获取单条数据 sqlite_version = cursor.fetchone() print("SQLite version : %s " % sqlite_version) # 关闭连接 conn.close() 

4. 连接MongoDB数据库

安装MongoDB客户端库

sudo apt update sudo apt install python3-pymongo 

Python代码示例

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

总结

  • MySQL: 使用 python3-mysqldb
  • PostgreSQL: 使用 python3-psycopg2
  • SQLite: 内置支持,无需额外库
  • MongoDB: 使用 python3-pymongo

根据你的需求选择合适的数据库和相应的Python库进行连接和操作。

0