Ubuntu Python数据库连接怎样实现

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

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

1. 连接MySQL数据库

首先,确保你已经安装了MySQL服务器。然后,使用pip安装mysql-connector-pythonPyMySQL库。

pip install mysql-connector-python

或者

pip install PyMySQL

使用mysql-connector-python连接MySQL

import mysql.connector

# 连接到MySQL数据库
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# 创建一个游标对象
mycursor = mydb.cursor()

# 执行SQL查询
mycursor.execute("SELECT * FROM yourtable")

# 获取查询结果
myresult = mycursor.fetchall()

for x in myresult:
  print(x)

使用PyMySQL连接MySQL

import pymysql

# 连接到MySQL数据库
conn = pymysql.connect(
  host='localhost',
  user='yourusername',
  password='yourpassword',
  db='yourdatabase'
)

# 创建一个游标对象
cursor = conn.cursor()

# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")

# 获取查询结果
results = cursor.fetchall()

for row in results:
  print(row)

2. 连接PostgreSQL数据库

首先,确保你已经安装了PostgreSQL服务器。然后,使用pip安装psycopg2库。

pip install psycopg2

使用psycopg2连接PostgreSQL

import psycopg2

# 连接到PostgreSQL数据库
conn = psycopg2.connect(
  dbname="yourdatabase",
  user="yourusername",
  password="yourpassword",
  host="localhost"
)

# 创建一个游标对象
cur = conn.cursor()

# 执行SQL查询
cur.execute("SELECT * FROM yourtable")

# 获取查询结果
rows = cur.fetchall()

for row in rows:
  print(row)

3. 连接SQLite数据库

SQLite是一个嵌入式数据库,不需要单独的服务器进程。使用Python内置的sqlite3模块即可连接。

import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect('yourdatabase.db')

# 创建一个游标对象
cursor = conn.cursor()

# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")

# 获取查询结果
rows = cursor.fetchall()

for row in rows:
  print(row)

注意事项

  1. 安全性:在实际应用中,不要将数据库的用户名和密码硬编码在代码中,可以使用环境变量或配置文件来存储这些敏感信息。
  2. 异常处理:在实际应用中,应该添加异常处理来捕获和处理数据库连接和查询过程中可能出现的错误。
  3. 资源管理:确保在使用完数据库连接后关闭连接,以释放资源。

通过以上步骤,你可以在Ubuntu上使用Python连接并操作数据库。

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

推荐阅读: 如何通过Ubuntu lsof命令查找进程