温馨提示×

Ubuntu下Python如何连接数据库

小樊
34
2025-10-31 11:17:55
栏目: 编程语言

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

  1. MySQL/MariaDB:

    要在Python中连接到MySQL或MariaDB数据库,可以使用mysql-connector-python库。首先,使用以下命令安装它:

    pip install mysql-connector-python
    

    然后,使用以下代码连接到数据库:

    import mysql.connector
    
    cnx = mysql.connector.connect(
        host="your_host",
        user="your_user",
        password="your_password",
        database="your_database"
    )
    
    cursor = cnx.cursor()
    
    # Your code to interact with the database goes here
    
    cursor.close()
    cnx.close()
    
  2. PostgreSQL:

    要在Python中连接到PostgreSQL数据库,可以使用psycopg2库。首先,使用以下命令安装它:

    pip install psycopg2
    

    然后,使用以下代码连接到数据库:

    import psycopg2
    
    cnx = psycopg2.connect(
        dbname="your_database",
        user="your_user",
        password="your_password",
        host="your_host",
        port="your_port"
    )
    
    cursor = cnx.cursor()
    
    # Your code to interact with the database goes here
    
    cursor.close()
    cnx.close()
    
  3. SQLite:

    要在Python中连接到SQLite数据库,可以使用内置的sqlite3库。使用以下代码连接到数据库:

    import sqlite3
    
    cnx = sqlite3.connect("your_database.db")
    
    cursor = cnx.cursor()
    
    # Your code to interact with the database goes here
    
    cursor.close()
    cnx.close()
    
  4. MongoDB:

    要在Python中连接到MongoDB数据库,可以使用pymongo库。首先,使用以下命令安装它:

    pip install pymongo
    

    然后,使用以下代码连接到数据库:

    from pymongo import MongoClient
    
    client = MongoClient("mongodb://your_user:your_password@your_host:your_port/your_database")
    
    db = client.your_database
    
    # Your code to interact with the database goes here
    

请根据您要连接的数据库类型选择合适的方法,并确保已安装相应的库。

0