0

This is my class for doing connection with 'libreria_udemy' database, but i have some problems.

package connection;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
    static String bd = "libreria_udemy";
    static String port = "3307";
    static String login = "root";
    static String password = "password";
    static String driver = "org.mariadb.jdbc.Driver";
    
    //jdbc:mysql://ip:puerto/bd
    //jdbc es el protocolo que se usa para conectarse a base de datos
    
    static String url = "jdbc:mysql://localhost:"+port+"/"+bd;
    
    Connection connection;
    
    public DBConnection() {
        
        try {
            System.out.println("holaa");
            System.out.println("mmm");
            Class.forName(driver);
            
            //this code does not appear:
            System.out.println("no aparezco");
            connection = DriverManager.getConnection(url, login, password);
            System.out.println(connection);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public Connection getConnection() {
        return connection;
    }
    
    public void desconectar() {
        connection = null; 
    }
}

And this class is for executing a simple query for updating my database. Also, Class.forName() is printing the driver in the console and I don't know why. I'm using MariaDB

package test;

import java.sql.Statement;
import connection.DBConnection;

public class OperacionesBD {

    public static void main(String[] args) {
        actualizarLibro(1, "Historia");
    }
    
    public static void actualizarLibro(int id, String genero) {
        DBConnection con = new DBConnection();
        String sql = "UPDATE libros SET genero ='" + genero + "'where id = "+id; 
        
        try {
            Statement st = con.getConnection().createStatement();
            st.executeQuery(sql);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            con.desconectar();
        }
    }
    
}

When I execute console shows this:

holaa
mmm
org.mariadb.jdbc.Driver
Cannot invoke "java.sql.Connection.createStatement()" because the return value of "connection.DBConnection.getConnection()" is null
  • You should not catch exceptions and continue on as if nothing happened. You probably got an exception creating a connection and thus `connection` of `DBConnection` is `null`, because - for example - you do not have the appropriate driver on the class path. As an aside, do not print the exception message, print the exception stack trace (with `e.printStackTrace()`). Also your reported output does not match the code shown (you're printing `org.mysql.jdbc.Driver`, while your code suggests you're trying to load `org.mariadb.jdbc.Driver`. – Mark Rotteveel Oct 13 '22 at 13:47

0 Answers0