Ubuntu Python数据库连接怎么操作

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

在Ubuntu上使用Python连接数据库,通常需要使用相应的数据库驱动程序。以下是一些常见数据库的连接操作:

  1. 连接MySQL数据库

首先,确保已经安装了MySQL数据库和Python的MySQL驱动程序mysql-connector-python。可以使用以下命令安装:

sudo apt-get install mysql-server
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()

# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)

# 获取查询结果
for row in cursor.fetchall():
    print(row)

# 关闭游标和连接
cursor.close()
cnx.close()
  1. 连接PostgreSQL数据库

首先,确保已经安装了PostgreSQL数据库和Python的PostgreSQL驱动程序psycopg2。可以使用以下命令安装:

sudo apt-get install postgresql postgresql-contrib
pip install psycopg2

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

import psycopg2

# 创建连接
conn = psycopg2.connect(
    dbname="your_database",
    user="your_user",
    password="your_password",
    host="your_host",
    port="your_port"
)

# 创建游标
cur = conn.cursor()

# 执行SQL查询
query = "SELECT * FROM your_table"
cur.execute(query)

# 获取查询结果
rows = cur.fetchall()
for row in rows:
    print(row)

# 关闭游标和连接
cur.close()
conn.close()
  1. 连接SQLite数据库

对于SQLite数据库,Python内置了sqlite3模块,无需额外安装。使用以下代码连接到SQLite数据库:

import sqlite3

# 创建连接
conn = sqlite3.connect('your_database.db')

# 创建游标
cursor = conn.cursor()

# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)

# 获取查询结果
rows = cursor.fetchall()
for row in rows:
    print(row)

# 关闭游标和连接
cursor.close()
conn.close()

根据需要选择合适的数据库驱动程序,并按照相应的步骤进行操作。

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

推荐阅读: Ubuntu中如何自动化日常任务