SQLite does not work

1

I'm trying to use sqlite, but it does not work for me.

I'm just making the structure this is the code of my class conexión() :

class conexion {
    String url = "C:\Users\Juan\Documents\NetBeansProjects\JavaApplication4\doc_sal.db";
    Connection connect;

    public void connect() {
        try {
            connect = DriverManager.getConnection("jdbc:sqlite:" + url);
            if (connect != null) {
                System.out.println("Conectado");
            }
        } catch (SQLException ex) {
            System.err.println("No se ha podido conectar a la base de datos\n" + ex.getMessage());
        }
    }

    public void close() {
        try {
            connect.close();
        } catch (SQLException ex) {
            Logger.getLogger(conexion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Here is my main class:

public class JavaApplication4 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        conexion cn=new conexion();
        cn.connect();
    }

}

But he always sends me this message

  

Could not connect to the database

     

No suitable driver found for jdbc: sqlite: C: \ Users \ Juan \ Documents \ NetBeansProjects \ JavaApplication4 \ doc_sal.db

I would like to know why it does not enter the database.

    
asked by Juan Enrique Feregrino Gomez 25.05.2018 в 15:34
source

1 answer

2

To establish the connection to a JDBC data source, you must not only use DriverManager.getConnection , you must also register the class that will be responsible for managing the connection with Class.forName() :

public void connect() {
    try {
        Class.forName("org.sqlite.JDBC");
        connect = DriverManager.getConnection("jdbc:sqlite:" + url);
        if (connect != null) {
            System.out.println("Conectado");
        }
    } catch (SQLException ex) {
        System.err.println("No se ha podido conectar a la base de datos\n" + ex.getMessage());
    } catch (ClassNotFoundException e) {
        System.err.println("El JAR no está correctamente agregado\n"
          + e.getMessage());
    }
}

As you can read in the official Java documentation:

  

A call to% co_of% causes the class named% co_of% to be initialized.

In Spanish:

  

A call to forName("X") causes the class named X to be initialized.

During the initialization process of the class it is registered as a JDBC driver.

In a similar way we could register the class using forName("X") :

DriverManager.registerDriver(new org.sqlite.JDBC());
    
answered by 25.05.2018 / 15:51
source