Ubuntu下Python与数据库如何连接

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

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

  1. MySQL数据库连接:

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

pip install mysql-connector-python

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

import mysql.connector

cnx = mysql.connector.connect(
    host="your_host",
    user="your_user",
    password="your_password",
    database="your_database"
)

cursor = cnx.cursor()

# 执行查询等操作

cursor.close()
cnx.close()
  1. PostgreSQL数据库连接:

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

pip install psycopg2

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

import psycopg2

conn = psycopg2.connect(
    dbname="your_database",
    user="your_user",
    password="your_password",
    host="your_host",
    port="your_port"
)

cursor = conn.cursor()

# 执行查询等操作

cursor.close()
conn.close()
  1. SQLite数据库连接:

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

import sqlite3

conn = sqlite3.connect("your_database.db")

cursor = conn.cursor()

# 执行查询等操作

cursor.close()
conn.close()
  1. MongoDB数据库连接:

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

pip install pymongo

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

from pymongo import MongoClient

client = MongoClient("mongodb://your_user:your_password@your_host:your_port/your_database")

db = client.your_database

# 执行查询等操作

请根据您使用的数据库类型选择合适的库,并将上述代码中的your_hostyour_useryour_passwordyour_database替换为您的数据库连接信息。

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

推荐阅读: Ubuntu如何编译zlib库