ubuntu

Ubuntu下Python数据库连接如何实现

小樊
52
2025-03-02 12:20:41
栏目: 编程语言

在Ubuntu下,你可以使用多种数据库连接库来实现Python与数据库的交互。以下是一些常见的数据库及其对应的Python连接库:

  1. MySQL数据库:

    • 使用mysql-connector-python库,可以通过pip安装:
      pip install mysql-connector-python
      
    • 示例代码:
      import mysql.connector
      
      # 连接数据库
      cnx = mysql.connector.connect(user='username', password='password',
                                    host='127.0.0.1',
                                    database='mydatabase')
      
      # 创建游标
      cursor = cnx.cursor()
      
      # 执行SQL查询
      query = ("SELECT * FROM mytable")
      cursor.execute(query)
      
      # 获取查询结果
      for row in cursor:
          print(row)
      
      # 关闭游标和连接
      cursor.close()
      cnx.close()
      
  2. PostgreSQL数据库:

    • 使用psycopg2库,可以通过pip安装:
      pip install psycopg2
      
    • 示例代码:
      import psycopg2
      
      # 连接数据库
      conn = psycopg2.connect(dbname="mydatabase", user="username",
                              password="password", host="127.0.0.1")
      
      # 创建游标
      cur = conn.cursor()
      
      # 执行SQL查询
      cur.execute("SELECT * FROM mytable")
      
      # 获取查询结果
      rows = cur.fetchall()
      for row in rows:
          print(row)
      
      # 关闭游标和连接
      cur.close()
      conn.close()
      
  3. SQLite数据库:

    • 使用sqlite3库,它是Python标准库的一部分,无需额外安装。
    • 示例代码:
      import sqlite3
      
      # 连接数据库
      conn = sqlite3.connect('mydatabase.db')
      
      # 创建游标
      cursor = conn.cursor()
      
      # 执行SQL查询
      cursor.execute("SELECT * FROM mytable")
      
      # 获取查询结果
      rows = cursor.fetchall()
      for row in rows:
          print(row)
      
      # 关闭游标和连接
      cursor.close()
      conn.close()
      
  4. MongoDB数据库:

    • 使用pymongo库,可以通过pip安装:
      pip install pymongo
      
    • 示例代码:
      from pymongo import MongoClient
      
      # 连接数据库
      client = MongoClient('mongodb://localhost:27017/')
      
      # 选择数据库
      db = client['mydatabase']
      
      # 选择集合
      collection = db['mycollection']
      
      # 查询所有文档
      documents = collection.find()
      
      for doc in documents:
          print(doc)
      

请根据你的实际需求选择合适的数据库和连接库,并确保已经安装了相应的Python库。在实际使用中,还需要处理异常和错误,以及正确管理数据库连接资源。

0
看了该问题的人还看了