可以从我的Java应用程序重置数据库到特定状态吗?

huangapple go评论67阅读模式
英文:

Can i reset database to a certain state from my Java application?

问题

我有一个Java应用程序,它通过JDBC连接到一个PostgreSQL数据库。我想在Java应用程序中创建一个方法,将数据库状态重置为我的.sql文件中的状态。

这个方法已经存在吗?如果不存在,我应该如何创建它?

编辑:我之所以问这个问题,是因为我正在尝试为我的学校项目的DAOs创建自包含的测试。由于这是一个学校项目,并且不是必需的,我避免使用我在网上找到的Hibernate/Spring Boot H2解决方案(对我的水平来说有点复杂)。

英文:

I have a Java application connected to a PostgreSQL database using a JDBC connection. I would like to have a method in the Java application that resets the database state to the one in my .sql file.

Does this method already exist ? If not, how should I go about making it ?

EDIT: The reason I'm asking is because I'm trying to have self-contained tests for my DAOs in my school project. Because it's a school project and it's not a requirement I'm avoiding the usage of hibernate/spring boot H2 solutions that I found on-line (a bit to complex for my level)

答案1

得分: 1

没有办法做到这一点。以下可能是一个可行的解决方案:

  • 创建一个模板数据库 my_template,并将你的 SQL 文件加载到其中。

  • 使用以下命令使数据库不可访问:

    ALTER DATABASE my_template ALLOW_CONNECTIONS FALSE;
    
  • 创建你的实际数据库:

    CREATE DATABASE mydb TEMPLATE my_template;
    
  • 然后,如果你想重置数据库,运行以下命令:

    DROP DATABASE mydb FORCE;
    CREATE DATABASE mydb TEMPLATE my_template;
    
英文:

There is no way to do that. The following might be a viable solution:

  • create a template database my_template and load your SQL file into it

  • make the database inaccessible with

    ALTER DATABASE my_template ALLOW_CONNECTIONS FALSE;
    
  • create your actual database with

    CREATE DATABASE mydb TEMPLATE my_template;
    
  • then, if you want to reset the database, run

    DROP DATABASE mydb FORCE;
    CREATE DATABASE mydb TEMPLATE my_template;
    

huangapple
  • 本文由 发表于 2023年7月12日 20:58:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76670846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定