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

相关推荐
fengye20716115 分钟前
板凳-------Mysql cookbook学习 (十)
学习·mysql·adb
蓝黑202016 分钟前
使用SSH tunnel访问内网的MySQL
mysql·ssh·proxy
夕泠爱吃糖40 分钟前
MySQL中的部分问题(1)
数据库·mysql
秃了也弱了。1 小时前
DBSyncer:开源数据库同步利器,MySQL/Oracle/ES/SqlServer/PG/
数据库·mysql·开源
玄辰星君2 小时前
PostgreSQL 入门教程
数据库·postgresql
喜欢踢足球的老罗2 小时前
使用 Spring Boot 3.3 和 JdbcTemplate 操作 MySQL 数据库
数据库·spring boot·mysql
文牧之2 小时前
PostgreSQL 的扩展pg_prewarm
运维·数据库·postgresql
行星0082 小时前
Postgresql字符串操作函数
数据库·postgresql
····懂···4 小时前
PostgreSQL 技术峰会,为您打造深度交流优质平台
数据库·postgresql
不太可爱的大白4 小时前
MySQL 索引:为使用 B+树作为索引数据结构,而非 B树、哈希表或二叉树?
数据结构·b树·mysql