Error creating Database in Java

0

I try to create and access a java database, I am using the postgresql-42.2.2 library. This is my method:

public static void main(String[] args) {
Connection c = null;
    try {
        Class.forName("org.postgresql.Driver");
        c = DriverManager
                .getConnection("jdbc:postgresql://localhost:5432/BaseDatos",
                        "postgres", "1234");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }

The error that gives me back is this:

jun 05, 2018 5:43:10 PM org.postgresql.core.v3.ConnectionFactoryImpl log
ADVERTENCIA: SQLException occurred while connecting to localhost:5432
org.postgresql.util.PSQLException: FATAL: no existe la base de datos «BaseDatos» (pgjdbc: autodetected server-encoding to be ISO-8859-1, if the message is not readable, please check database logs and/or host, port, dbname, user, password, pg_hba.conf)
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2433)
at org.postgresql.core.v3.QueryExecutorImpl.readStartupMessages(QueryExecutorImpl.java:2566)
at org.postgresql.core.v3.QueryExecutorImpl.<init>(QueryExecutorImpl.java:131)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:210)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
at org.postgresql.Driver.makeConnection(Driver.java:452)
at org.postgresql.Driver.connect(Driver.java:254)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at creando.y.usando.bd.CreandoYUsandoBD.main(CreandoYUsandoBD.java:18)

Could you tell me how to fix it? I would greatly appreciate your help. Greetings.

    
asked by Luis Ramiro 05.06.2018 в 23:45
source

2 answers

0

Yes and I did not realize that mistake. I was not creating the Database. This way I am already creating it.

public  void creandoBD(String[] args) {
    Connection c = null;
    Statement stmt = null;
    try {
        Class.forName("org.postgresql.Driver");
        c = DriverManager
                .getConnection("jdbc:postgresql://localhost:5432/",
                        "postgres", "1234");
        stmt = c.createStatement();
        String sql = "CREATE DATABASE Basedatos2";
        stmt.executeUpdate(sql);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }

}

The scare is that now I get an error if the database already exists.

The question would be: How to modify this code so that each time you run the program before creating the database, see if it already exists and just connect?

    
answered by 06.06.2018 в 01:20
0

Try this way.

    PreparedStatement ps = null;
    Connection c = null;

    String selectSQL = "SELECT datname FROM pg_catalog.pg_database WHERE LOWER(datname) = LOWER(?)";
    String nombreBD="Pon-aqui-el-nombre-de-la-bd";

    try {

        Class.forName("org.postgresql.Driver");
        c = DriverManager
            .getConnection("jdbc:postgresql://localhost:5432/BaseDatos",
                    "postgres", "1234");
        ps = c.prepareStatement(selectSQL);
        ps.setString(1, nombreBD);

        ResultSet rs = ps.executeQuery();
        /*Verificar si encontró datos*/
        if (!rs.isBeforeFirst()) {    
            System.out.println("No existe BD, vamos a crearla"); 
            String createSQL = "CREATE DATABASE ?";
            ps = c.prepareStatement(createSQL);
            ps.setString(1, nombreBD);
            int filas = ps.executeUpdate();
            System.out.println("Se creó "+ filas +" base de datos"); 
        } 

    } catch (Exception e) {

        e.printStackTrace();
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);

    /*Cerrar recursos*/
    } finally {

        if (ps != null) {
            ps.close();
        }

        if (c != null) {
            c.close();
        }

    }
    
answered by 06.06.2018 в 03:20