0

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 {

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

            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){

                conn.close();

            }

            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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So I have to use the namespace or i guess in Java its the "class name" of the Class then. Could I create that static Connect() method as a global function?
There are no global functions in Java. You need to import classes individually. Static members can also be imported to save some boilerplate, e.g. import static com.mypackage.Connect.connect; after which you don't need to specify the class name to invoke that method within the importing class.
Thanks I didn't know you can do static imports, I am coldfusion programmer and I started with C# I am learning Java so I can use it in conjunction with Coldfusion. C# just added static imports in version 6. How long has java been able to do it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.