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 和 Redis:原理、区别、项目用法全解析(建议收藏)
redis·mysql·项目实战
IvorySQL4 小时前
PostgreSQL 技术日报 (3月5日)|规划器控制力升级,内核能力再进阶
数据库·postgresql·开源
武子康4 小时前
大数据-241 离线数仓 - 实战:电商核心交易数据模型与 MySQL 源表设计(订单/商品/品类/店铺/支付)
大数据·后端·mysql
用户8307196840821 天前
MySQL 查询优化 30 条封神技巧:用好索引,少耗资源,查询快到飞起
mysql
Nyarlathotep01131 天前
事务隔离级别
sql·mysql
IvorySQL1 天前
PostgreSQL 技术日报 (3月4日)|硬核干货 + 内核暗流一网打尽
数据库·postgresql·开源
Nyarlathotep01131 天前
SQL的事务控制
sql·mysql
用户86178277365181 天前
MySQL 8.0从库宕机排查实录:中继日志膨胀引发的连锁故障复盘
mysql
IvorySQL2 天前
双星闪耀温哥华:IvorySQL 社区两项议题入选 PGConf.dev 2026
数据库·postgresql·开源
随风飘的云2 天前
mysql的innodb引擎对可重复读做了那些优化,可以避免幻读
mysql