首页主机资讯Python在Ubuntu上如何进行数据库连接

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

时间2025-10-16 19:31:03发布访客分类主机资讯浏览682
导读:在Ubuntu上使用Python连接数据库,通常需要安装相应的数据库驱动和库。以下是一些常见数据库的连接方法: 1. 连接MySQL数据库 安装MySQL客户端库 sudo apt update sudo apt install pytho...

在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库进行连接和操作。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Python在Ubuntu上如何进行数据库连接
本文地址: https://pptw.com/jishu/728308.html
Linux上MongoDB版本升级步骤 Python在Ubuntu上如何进行数据可视化

游客 回复需填写必要信息