Jesse Jesse - 1 year ago 73
SQL Question

Create an SQLite Connection in a static method in Java

I want to create a static method in Java to abstract connecting to an SQLite database

Here is my code for the Connect Class:

public class Connect {

public static Connection Connect(String connection, Boolean create) throws ClassNotFoundException, SQLException, FileNotFoundException {

Connection conn = null;

try {


if(create == false){

try {

FileInputStream f = new FileInputStream(connection);
conn = DriverManager.getConnection("jdbc:sqlite:"+connection);

} catch(Exception NoDB) {
throw NoDB;

} else {

conn = DriverManager.getConnection("jdbc:sqlite:"+connection);


return conn;

} catch(Exception e){

if(conn != null){



throw e;



I want to be able to call the Connect Class like this

Connection conn = Connect();

I am using Intellij and the IDE Keeps suggesting this code to

(Connection) conn = new Connect();

I made the methods static and I am importing the Class. What am I doing wrong how to make the code work that way. I am return a type connection from the static method.

Answer Source

If you're creating a static method for acquiring the connection, then you shouldn't be creating an instance of the utility class (using the new operator) in the first place.

Static methods are accessed by the class name, so just use Connection conn = Connect.Connect(...) instead. And note that according to Java style conventions, method names should start with a lower-case letter.