MySQL 和 PostgreSQL 的使用案例

MySQL 和 PostgreSQL 的使用案例

在实际开发中,无论是使用 MySQL 还是 PostgreSQL,都会涉及一些常见的数据库操作,如查询、数据新增,以及如何在代码中连接数据库。本文将通过具体实例,演示如何在 MySQL 和 PostgreSQL 中执行常见操作,并讨论长期连接和短期连接的概念。

一、数据库连接

1. MySQL 连接示例 (使用 Python)
python 复制代码
import mysql.connector

# 数据库连接配置
config = {
    'user': 'your_username',
    'password': 'your_password',
    'host': 'localhost',
    'database': 'your_database',
}

try:
    # 建立连接
    conn = mysql.connector.connect(**config)
    if conn.is_connected():
        print('Connected to MySQL database')
finally:
    conn.close()
2. PostgreSQL 连接示例 (使用 Python)
python 复制代码
import psycopg2

# 数据库连接配置
config = {
    'dbname': 'your_database',
    'user': 'your_username',
    'password': 'your_password',
    'host': 'localhost',
}

try:
    # 建立连接
    conn = psycopg2.connect(**config)
    print('Connected to PostgreSQL database')
finally:
    conn.close()

二、数据查询 (SELECT)

1. 在 MySQL 中使用 SELECT 查询
python 复制代码
import mysql.connector

config = {
    'user': 'your_username',
    'password': 'your_password',
    'host': 'localhost',
    'database': 'your_database',
}

try:
    conn = mysql.connector.connect(**config)
    cursor = conn.cursor()

    # 执行查询
    cursor.execute("SELECT id, name FROM employees")

    # 获取查询结果
    for (id, name) in cursor:
        print(f"{id}: {name}")

finally:
    cursor.close()
    conn.close()
2. 在 PostgreSQL 中使用 SELECT 查询
python 复制代码
import psycopg2

config = {
    'dbname': 'your_database',
    'user': 'your_username',
    'password': 'your_password',
    'host': 'localhost',
}

try:
    conn = psycopg2.connect(**config)
    cursor = conn.cursor()

    # 执行查询
    cursor.execute("SELECT id, name FROM employees")

    # 获取查询结果
    for record in cursor:
        print(f"{record[0]}: {record[1]}")

finally:
    cursor.close()
    conn.close()

三、数据新增 (INSERT)

1. 在 MySQL 中使用 INSERT 新增数据
python 复制代码
import mysql.connector

config = {
    'user': 'your_username',
    'password': 'your_password',
    'host': 'localhost',
    'database': 'your_database',
}

try:
    conn = mysql.connector.connect(**config)
    cursor = conn.cursor()

    # 执行插入
    add_employee = ("INSERT INTO employees "
                    "(name, department_id) "
                    "VALUES (%s, %s)")
    data_employee = ('John Doe', 1)
    cursor.execute(add_employee, data_employee)

    # 提交数据
    conn.commit()

finally:
    cursor.close()
    conn.close()
2. 在 PostgreSQL 中使用 INSERT 新增数据
python 复制代码
import psycopg2

config = {
    'dbname': 'your_database',
    'user': 'your_username',
    'password': 'your_password',
    'host': 'localhost',
}

try:
    conn = psycopg2.connect(**config)
    cursor = conn.cursor()

    # 执行插入
    add_employee = "INSERT INTO employees (name, department_id) VALUES (%s, %s)"
    data_employee = ('John Doe', 1)
    cursor.execute(add_employee, data_employee)

    # 提交数据
    conn.commit()

finally:
    cursor.close()
    conn.close()

四、是否长连接

长连接与短连接
  • 短连接

    • 每次执行数据库操作时建立和关闭连接。

    • 适用于频繁的小量查询操作或脚本执行。

    • 例:

      python 复制代码
      try:
          conn = psycopg2.connect(**config)
          cursor = conn.cursor()
          cursor.execute("SELECT * FROM employees")
          conn.commit()
      finally:
          cursor.close()
          conn.close()
  • 长连接

    • 程序启动时建立数据库连接,并在整个程序运行期间保持连接。

    • 适用于高频率、大数据量的查询操作,如 Web 服务器的数据库连接。

    • 一般使用连接池来管理长连接,减少连接建立和断开的开销。

    • 连接池示例(PostgreSQL 和 SQLAlchemy):

      python 复制代码
      from sqlalchemy import create_engine
      
      # 创建数据库连接池
      engine = create_engine('postgresql+psycopg2://username:password@localhost/your_database')
      
      # 使用连接池中的连接
      with engine.connect() as connection:
          result = connection.execute("SELECT * FROM employees")
          for row in result:
              print(row)

五、总结

MySQL 和 PostgreSQL 在许多方面都有相似之处,都可以用于执行常见的数据库操作如查询、数据新增等。然而,它们在性能、特性和连接管理方面存在一些差异。MySQL 可能更适合轻量级应用和简化管理,而 PostgreSQL 则更适合复杂查询和重负载场景。

相关推荐
后端码匠3 小时前
MySQL 8.0安装(压缩包方式)
android·mysql·adb
问道飞鱼5 小时前
【数据库知识】Mysql进阶-高可用MHA(Master High Availability)方案
数据库·mysql·adb·高可用·mha
tiging5 小时前
centos7.x下,使用宝塔进行主从复制的原理和实践
数据库·mysql·adb·主从复制
一只fish6 小时前
MySQL 8.0 OCP 1Z0-908 题目解析(2)
数据库·mysql
董可伦7 小时前
Dinky 安装部署并配置提交 Flink Yarn 任务
android·adb·flink
大学生小郑8 小时前
Go语言八股之Mysql基础详解
mysql·面试
Lw老王要学习8 小时前
Linux数据库篇、第一章_02_MySQL的使用增删改查
linux·运维·数据库·mysql·云计算·it
林下清风~8 小时前
MySQL——九、锁
数据库·mysql
xiaogai_gai9 小时前
有效的聚水潭数据集成到MySQL案例
android·数据库·mysql
web1309332039810 小时前
Mysql的安装配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
数据库·mysql