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

相关推荐
老朋友此林34 分钟前
go语言学习笔记:gin + gorm + mysql 用户增删改查案例入门
mysql·golang·gin
结衣结衣.1 小时前
【MySQL】库的操作
linux·数据库·mysql
Code哈哈笑3 小时前
Idea连接远程云服务器上的MySQL,开放云服务器端口
服务器·后端·mysql·spring
小王子玫瑰狐3 小时前
数据库之MySQL
数据库·mysql
沸材7 小时前
MySQL——事务
数据库·mysql·事务
文牧之9 小时前
MySQL 修改用户密码
运维·数据库·mysql
pwzs12 小时前
理解最左前缀原则:联合索引命中规则全解析(含流程图)
数据库·sql·mysql
程序员总部12 小时前
Python正则表达式有哪些常用匹配字符?
python·mysql·正则表达式
杭州杭州杭州13 小时前
ubuntu 18.04安装tomcat,zookeeper,kafka,hadoop,MySQL,maxwell
hadoop·mysql·ubuntu·zookeeper·kafka·tomcat
程序猿John14 小时前
Mysql读写分离(2)-中间件mycat和实践方案
数据库·mysql·中间件