ubuntu

Ubuntu Python与数据库如何连接

小樊
34
2025-03-16 15:00:37
栏目: 编程语言

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

  1. MySQL/MariaDB:

要使用Python连接到MySQL或MariaDB数据库,你可以使用mysql-connector-python库(由MySQL官方提供)或PyMySQL库(一个纯Python实现的MySQL客户端库)。

安装库:

pip install mysql-connector-python

pip install pymysql

使用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()

# 执行查询等操作

cursor.close()
cnx.close()

使用PyMySQL连接数据库:

import pymysql

cnx = pymysql.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

使用psycopg2连接数据库:

import psycopg2

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

cursor = cnx.cursor()

# 执行查询等操作

cursor.close()
cnx.close()
  1. SQLite:

要使用Python连接到SQLite数据库,你可以使用内置的sqlite3库。

使用sqlite3连接数据库:

import sqlite3

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

cursor = conn.cursor()

# 执行查询等操作

cursor.close()
conn.close()

这些示例展示了如何使用Python连接到不同的数据库。在实际应用中,你可能需要根据需求执行查询、插入、更新和删除等操作。请查阅相应库的文档以获取更多详细信息。

0
看了该问题的人还看了