ubuntu

Ubuntu下Python数据库连接如何操作

小樊
44
2025-12-22 10:54:15
栏目: 编程语言

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

  1. MySQL

首先,安装MySQL数据库和Python的MySQL驱动:

sudo apt-get install mysql-server
pip install mysql-connector-python

然后,使用Python连接MySQL数据库:

import mysql.connector

# 创建连接
cnx = mysql.connector.connect(
    host="localhost",
    user="your_username",
    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驱动:

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

然后,使用Python连接PostgreSQL数据库:

import psycopg2

# 创建连接
cnx = psycopg2.connect(
    dbname="your_database",
    user="your_username",
    password="your_password",
    host="localhost"
)

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

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

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

# 关闭游标和连接
cursor.close()
cnx.close()
  1. SQLite

SQLite是一个轻量级的数据库,无需安装额外的驱动。使用Python内置的sqlite3库连接SQLite数据库:

import sqlite3

# 创建连接
cnx = sqlite3.connect("your_database.db")

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

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

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

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

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

0
看了该问题的人还看了