Main class where the code is running :
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:5432/postgres";
// Database credentials
static final String USER = "postgres";
static final String PASS = "postgres";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 3: Execute a query
ScriptRunner sr = new ScriptRunner(conn);
//Creating a reader object
Reader reader = new BufferedReader(new FileReader("C:\\PROJECTS\\SQL\\src\\main\\resources\\createDatabaseAndUser.sql"));
//Running the script
sr.runScript(reader);
And this is the file createDatabaseAndUser.sql :
CREATE DATABASE aNewDb;
I am trying to run my program in IDEA and I receive the ERROR :
Connecting to database...
CREATE DATABASE aNewDb
Error executing: CREATE DATABASE aNewDb.
Cause: org.postgresql.util.PSQLException: ERROR: CREATE DATABASE cannot run inside a transaction block
When I run this script without program ( without Main.class ) everything is OK and the database created without any problems.
Copyright Notice:Content Author:「Kuzma」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60012171/error-executing-create-database-anewdb-cause-org-postgresql-util-psqlexcepti