ubuntu

Python在Ubuntu中的数据库连接如何实现

小樊
54
2025-05-05 22:01:01
栏目: 编程语言

在Ubuntu系统中,使用Python连接数据库通常涉及以下几个步骤:

  1. 安装数据库:首先,你需要在Ubuntu上安装所需的数据库。例如,如果你想使用MySQL,你可以使用以下命令安装MySQL服务器:

    sudo apt update
    sudo apt install mysql-server
    

    对于PostgreSQL,可以使用:

    sudo apt update
    sudo apt install postgresql postgresql-contrib
    
  2. 安装Python数据库驱动:接下来,你需要安装一个Python库来与数据库通信。对于MySQL,常用的库是mysql-connector-pythonPyMySQL。对于PostgreSQL,可以使用psycopg2

    使用pip安装这些库的命令如下:

    pip install mysql-connector-python
    # 或者
    pip install PyMySQL
    # 对于PostgreSQL
    pip install psycopg2-binary
    
  3. 编写Python代码:现在你可以编写Python代码来连接数据库。以下是使用mysql-connector-python连接MySQL数据库的一个基本示例:

    import mysql.connector
    from mysql.connector import Error
    
    try:
        connection = mysql.connector.connect(
            host='localhost',
            database='your_database',
            user='your_username',
            password='your_password'
        )
    
        if connection.is_connected():
            db_Info = connection.get_server_info()
            print("Connected to MySQL Database version ", db_Info)
            cursor = connection.cursor()
            cursor.execute("SELECT DATABASE();")
            record = cursor.fetchone()
            print("You're connected to database: ", record)
    
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL connection is closed")
    

    对于PostgreSQL,代码会略有不同:

    import psycopg2
    
    try:
        connection = psycopg2.connect(
            dbname="your_database",
            user="your_username",
            password="your_password",
            host="localhost"
        )
        cursor = connection.cursor()
        cursor.execute("SELECT version();")
        db_version = cursor.fetchone()
        print("Connected to PostgreSQL version:", db_version)
    
    except psycopg2.Error as e:
        print("Unable to connect to the database")
        print(e)
    finally:
        if connection:
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
    
  4. 运行Python脚本:保存你的Python脚本,并在终端中运行它。如果一切设置正确,你的脚本应该能够连接到数据库并执行查询。

请确保将上述代码中的your_databaseyour_usernameyour_password替换为你的实际数据库名称、用户名和密码。此外,根据你的数据库配置,可能需要调整连接参数,例如主机地址(如果不是本地数据库)或端口号。

0
看了该问题的人还看了