Question

I have created a simple Java connection script in Java to connect to a database shown below.

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

public class dbconn {

public static void main(String[] args) throws ClassNotFoundException
{

Class.forName("org.sqlite.JDBC");

Connection connection = null;  
try
{
  // create a database connection
  connection = DriverManager.getConnection("jdbc:sqlite:C:/Program Files (x86)/Spiceworks/db/spiceworks_prod.db");
  Statement statement = connection.createStatement();
  statement.setQueryTimeout(30);  // set timeout to 30 sec.                  
}
catch(SQLException e)
{
  // if the error message is "out of memory", 
  // it probably means no database file is found
  System.err.println(e.getMessage());
}
finally
{
  try
  {
    if(connection != null)
        connection.close();

  }
  catch(SQLException e)
  {
    // connection close failed.
    System.err.println(e);
  }
}
}
}

Now I have tested this connection via some SQL queries inside the dbconn script and it works.

However my question is, how would Icall this instance of the database into another form in the same project to preform the same SQL queries which are:

 ResultSet resultSet = null;  

  resultSet = statement.executeQuery("SELECT * FROM users");  
     while (resultSet.next()) 
     {  
         System.out.println("EMPLOYEE Email: " + resultSet.getString("email"));  
     }

No correct solution

OTHER TIPS

You can retain and reuse the Connection, saving it probably in some static field. If you access it from multiple threads, SQLite must work in the Serialized mode. You must have the code somewhere to re-establish the connection if it has been lost for some reason.

If the use of Connection is not heavy, you can also have some method that opens it and close when no longer needed, better inside the finally block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top