JDBC Sqlite - Java

Asked

Viewed 1,635 times

3

Good afternoon,

How do I make the connection to the Sqlite BD? I made the connection class like this.

package model;

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

public class Conexao {
    public static void main( String args[] ) {

        // Variáveis
        Connection con  =   null;  
        String driver   =   "org.postgresql.Driver";
        String dir      =   "jdbc:sqlite:test.db";
        String user     =   "postgres_usuario";  
        String pass     =   "postgres_senha";    

        try {  
            Class.forName("org.sqlite.JDBC");    
            con = (Connection) DriverManager.getConnection(dir, user, pass);    
        } catch (ClassNotFoundException ex) {  
            ex.printStackTrace();
        } catch (SQLException e) {  
            e.printStackTrace();  
        }    
    }
}

Thanks in advance!

  • You’re not mixing data from a bank sqlite with a postgresql? It could also include the error generated in your question?

  • Yes that’s what I tried to do. Anything else that changes is not just Class.forName("Content")?

1 answer

3

You can make the connection like this:

import java.sql.*;  

public class Test {  
    private Connection conexao;  
    public Statement statement;  
    public ResultSet resultset;  
    public PreparedStatement prep;  
  public void conecta() throws Exception {  
    Class.forName("org.sqlite.JDBC");  
    conexao =  
      DriverManager.getConnection("jdbc:sqlite:test.db");  
    statement = conexao.createStatement();  
   conexao.setAutoCommit(false);  
    conexao.setAutoCommit(true);  

  }  
  public void exec(String sql) throws Exception {  
   resultset = statement.executeQuery(sql);  
  }  
public void desconecta()  
       {  
            boolean result = true;  
            try  
            {  
              conexao.close();  
              JOptionPane.showMessageDialog(null,"banco fechado");  
            }  
            catch(SQLException fecha)  
            {  
              JOptionPane.showMessageDialog(null,"Não foi possivel "+  
                      "fechar o banco de dados: "+fecha);  
              result = false;  
          }  

     }  
}  

on this line ("jdbc:sqlite:test.db"); where this "test.db" is the name of your database.

ps: Don’t forget to download the ODBC sqlite driver ^^

  • I can’t vote because the site says I don’t have "15 points" of reputation. Thanks Dante!

  • Don’t worry Mark the answer as right and when you have the 15 points come back here to score as useful! You’re welcome! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.