Create database and tables from java

3

I am developing a SaaS and I am in the database part, what I want to do is create a database in postgresql for each client that registers but I do not know how to create them from java since the code that I have is the next:

CREATE DATABASE "Inventarios"
WITH OWNER = postgres
ENCODING = 'UTF8'
TABLESPACE = pg_default
LC_COLLATE = 'Spanish_Mexico.1252'
LC_CTYPE = 'Spanish_Mexico.1252'
CONNECTION LIMIT = -1;

However I'm not sure if that way I should work because I can not execute it because in the connection string it asks for the name of the database and that is what is not yet created, I also found information regarding create it using .bat files in windows but I do not know how to do it in linux

    
asked by Leo T 20.12.2016 в 16:27
source

2 answers

4

Unless you use a framework for databases like Hibernate you will have to open the connection (with the name you put as parameters) and launch the SQL code to create tables manually. Example:

PreparedStatement ps = connection.prepareStatement("CREATE TABLE IF NOT EXISTS user(user_id SERIAL NOT NULL PRIMARY KEY,username varchar(225) NOT NULL UNIQUE,password varchar(225),islogged varchar(10))");
ps.executeUpdate();
ps.close();

* The String [] args parameter of the main method contains the parameters passed from the operating system, you will have to pass them from your bat or sh to your compiled java .class

* To connect to the database and create it from Java you must connect to the maintenance database that can not be deleted and launch the command.

CREATE DATABASE testdb;
    
answered by 20.12.2016 / 16:32
source
1

This is the best way to create a database ... you do not need to use the bd of the system.

String drive="jdbc: mysql: // localhost: 3306 /";

    try {
        cnx = (Connection) DriverManager.getConnection(drive,user,paswd);
        ps = cnx.prepareStatement("CREATE DATABASE "+bd);
        ps.executeUpdate();
        ps.close();
    } catch (SQLException ex) {
        System.out.println(ex);
    }

This code is used in my system and has always worked.

    
answered by 02.02.2018 в 08:27