linux

Linux环境下Python如何连接数据库

小樊
41
2025-09-25 01:30:42
栏目: 编程语言

在Linux环境下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的Python库:

  1. MySQL: 使用mysql-connector-pythonPyMySQL库。 安装:pip install mysql-connector-pythonpip install pymysql 示例代码(使用mysql-connector-python):

    import mysql.connector
    
    connection = mysql.connector.connect(
        host="localhost",
        user="your_username",
        password="your_password",
        database="your_database"
    )
    
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table")
    result = cursor.fetchall()
    
    for row in result:
        print(row)
    
    cursor.close()
    connection.close()
    
  2. PostgreSQL: 使用psycopg2库。 安装:pip install psycopg2pip install psycopg2-binary 示例代码:

    import psycopg2
    
    connection = psycopg2.connect(
        dbname="your_database",
        user="your_username",
        password="your_password",
        host="localhost"
    )
    
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table")
    result = cursor.fetchall()
    
    for row in result:
        print(row)
    
    cursor.close()
    connection.close()
    
  3. SQLite: 使用内置的sqlite3库。 示例代码:

    import sqlite3
    
    connection = sqlite3.connect("your_database.db")
    
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table")
    result = cursor.fetchall()
    
    for row in result:
        print(row)
    
    cursor.close()
    connection.close()
    
  4. MongoDB: 使用pymongo库。 安装:pip install pymongo 示例代码:

    from pymongo import MongoClient
    
    client = MongoClient("mongodb://your_username:your_password@localhost:27017/your_database")
    
    db = client.your_database
    collection = db.your_table
    
    for document in collection.find():
        print(document)
    

请根据您使用的数据库类型选择合适的库,并确保已正确安装。在运行示例代码之前,请替换为您自己的数据库连接信息。

0
看了该问题的人还看了