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 则更适合复杂查询和重负载场景。

相关推荐
2301_7736436237 分钟前
华为云存储实验
网络·mysql·华为云
quan26312 小时前
20260529,日常开发-数据库主从问题
java·mysql·主从·延迟
DIY源码阁5 小时前
JavaSwing宿舍管理系统 - MySQL版
java·数据库·mysql·eclipse
cfm_29145 小时前
MySQL8.0 InnoDB Cluster
数据库·mysql
暴躁小师兄数据学院6 小时前
【AI大数据工程师特训笔记】第10讲:数据库用户、权限管理、数据库约束
大数据·数据库·笔记·sql·postgresql
暴躁小师兄数据学院7 小时前
【AI大数据工程师特训笔记】第02讲:PostgreSQL数据库生态全景
大数据·数据库·人工智能·postgresql
夜微凉47 小时前
三、MySQL
android·数据库·mysql
暴躁小师兄数据学院7 小时前
【AI大数据工程师特训笔记】第11讲:正则表达式与正则函数
数据库·mysql
IT龟苓膏8 小时前
MySQL InnoDB 内存结构与性能调优:Buffer Pool、脏页、刷盘、临时表和 filesort 一篇讲清
数据库·mysql
加号38 小时前
【MySQL】 审计功能深度解析:从原理到落地实践
数据库·mysql