ubuntu

Ubuntu Python数据库连接如何实现

小樊
52
2025-04-25 19:51:36
栏目: 编程语言

在Ubuntu上使用Python连接数据库,通常需要使用数据库的官方驱动或第三方库。以下是一些常见数据库的连接方法:

1. 连接MySQL数据库

使用mysql-connector-python

首先,安装库:

pip install mysql-connector-python

然后,编写Python代码连接MySQL数据库:

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数据库

使用psycopg2

首先,安装库:

pip install psycopg2

然后,编写Python代码连接PostgreSQL数据库:

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数据库

使用sqlite3

Python标准库中已经包含了sqlite3模块,无需额外安装。

编写Python代码连接SQLite数据库:

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数据库

使用pymongo

首先,安装库:

pip install pymongo

然后,编写Python代码连接MongoDB数据库:

from pymongo import MongoClient

# 创建客户端
client = MongoClient("mongodb://localhost:27017/")

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

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

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

for document in documents:
    print(document)

总结

以上是几种常见数据库在Ubuntu上使用Python连接的示例。根据你使用的数据库类型,选择相应的库并进行安装和配置即可。确保你的数据库服务已经启动并运行在指定的主机和端口上。

0
看了该问题的人还看了