JDBC SQLite - Java

3

Good afternoon,

How do I make the connection to SQLite DB? 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();  
        }    
    }
}

Thank you in advance!

    
asked by anonymous 31.07.2014 / 18:27

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;  
          }  

     }  
}  

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

ps: Do not forget to download the sqlite ODBC driver ^^

    
31.07.2014 / 18:51