ubuntu

Ubuntu如何用Python连接数据库

小樊
48
2025-07-05 15:01:56
栏目: 编程语言

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

  1. 安装数据库:首先,你需要在Ubuntu上安装你想要连接的数据库。例如,如果你想连接MySQL数据库,你可以使用以下命令安装MySQL服务器:
sudo apt update
sudo apt install mysql-server

对于PostgreSQL,可以使用:

sudo apt update
sudo apt install postgresql postgresql-contrib
  1. 安装Python数据库驱动:接下来,你需要安装相应的Python库来连接数据库。对于MySQL,常用的库是mysql-connector-pythonpymysql。对于PostgreSQL,可以使用psycopg2

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

# 对于MySQL
pip install mysql-connector-python
# 或者
pip install pymysql

# 对于PostgreSQL
pip install psycopg2

如果你使用的是Python 3,可能需要使用pip3来安装。

  1. 编写Python代码连接数据库:安装好数据库和相应的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")

请确保将your_databaseyour_usernameyour_password替换为你的实际数据库名称、用户名和密码。

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

import psycopg2

try:
    connection = psycopg2.connect(
        dbname='your_database',
        user='your_username',
        password='your_password',
        host='localhost'
    )
    print("Connected to PostgreSQL database")

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")

同样地,替换your_databaseyour_usernameyour_password为你的实际数据库信息。

  1. 运行Python脚本:保存你的Python脚本,并在终端中运行它:
python your_script.py
# 或者如果你使用的是Python 3
python3 your_script.py

确保你的数据库服务正在运行,并且你的防火墙设置允许数据库连接。如果你遇到任何连接问题,请检查数据库服务的状态、用户权限和网络配置。

0
看了该问题的人还看了