Ubuntu Python数据库连接怎么弄

979
2025/3/26 18:32:09
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu上使用Python连接数据库,通常需要以下几个步骤:

  1. 安装数据库驱动:根据你使用的数据库类型,你需要安装相应的Python驱动。以下是一些常见数据库的驱动安装方法:

    • MySQL: 使用pip安装mysql-connector-python包:

      pip install mysql-connector-python
      
    • PostgreSQL: 使用pip安装psycopg2包:

      pip install psycopg2
      

      或者安装psycopg2-binary包(不需要编译环境):

      pip install psycopg2-binary
      
    • SQLite: Python标准库中已经包含了SQLite3模块,无需额外安装。

    • MongoDB: 使用pip安装pymongo包:

      pip install pymongo
      
  2. 编写Python代码:根据你使用的数据库和驱动,编写相应的Python代码来连接数据库。以下是一些示例:

    • MySQL:

      import mysql.connector
      
      cnx = mysql.connector.connect(user='username', password='password',
                                    host='localhost',
                                    database='your_database')
      cursor = cnx.cursor()
      
      query = ("SELECT * FROM your_table")
      cursor.execute(query)
      
      for row in cursor:
          print(row)
      
      cursor.close()
      cnx.close()
      
    • PostgreSQL:

      import psycopg2
      
      conn = psycopg2.connect(dbname='your_database', user='username',
                              password='password', host='localhost')
      cursor = conn.cursor()
      
      cursor.execute("SELECT * FROM your_table")
      rows = cursor.fetchall()
      
      for row in rows:
          print(row)
      
      cursor.close()
      conn.close()
      
    • SQLite:

      import sqlite3
      
      conn = sqlite3.connect('your_database.db')
      cursor = conn.cursor()
      
      cursor.execute("SELECT * FROM your_table")
      rows = cursor.fetchall()
      
      for row in rows:
          print(row)
      
      cursor.close()
      conn.close()
      
    • MongoDB:

      from pymongo import MongoClient
      
      client = MongoClient('mongodb://username:password@localhost:27017/your_database')
      db = client['your_database']
      collection = db['your_table']
      
      documents = collection.find()
      
      for doc in documents:
          print(doc)
      
  3. 运行Python代码:在终端中运行你的Python脚本,例如:

    python your_script.py
    

请根据你的实际情况替换示例中的数据库连接信息、表名等。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: kdevelop在ubuntu上有哪些成功案例