louboulos
louboulos

Reputation: 27

How to check if database credentials are correct in Java?

I have these two methods. I can't seem to get it to work. The first method initializes the database connection and the second runs an other GUI after the log in procedure. I want to check if credentials are correct first before calling the GUI Class. Anybody has any suggestions on how I can achieve that?

    public void getDBConnection() throws SQLException{
    userid = usernameF.getText();
    password = passwordF.getText();
    OracleDataSource ds;
    ds = new OracleDataSource();
    ds.setURL(jdbcUrl);
    conn = ds.getConnection(userid,password);

    if(conn){
    System.out.println("Connected Successfully to Database. User: " + userid);
    }
    else {
        System.out.println("Wrong Data");
    }

}



    private void loginbox_actionPerformed(ActionEvent e) {


    try {
        getDBConnection();
    } 
    catch (SQLException f) {
        status.setText("INVALID USERNAME OR PASSWORD");
        }



    GUI guid = new GUI();
    guid.setVisible(true);
    guid.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    System.out.println(userid + " " + password);


}

Upvotes: 0

Views: 1211

Answers (3)

René Link
René Link

Reputation: 51353

You can execute a statement that has no effect to see if a connection works.

// for example
select 1 from dual; 

Connection pools use this strategy to check if a connection is valid before returning it.

See http://docs.oracle.com/cd/E13222_01/wls/docs81/ConsoleHelp/jdbc_connection_pools.html for a verify statement overview (Table 127-1 Default Test Table Name by DBMS).

Upvotes: 1

Learner
Learner

Reputation: 221

Return true or false from getDBConnection() method on the basis of connection logic then use the value in login method and perform the action of activating GUI or not

Upvotes: 0

frostmatthew
frostmatthew

Reputation: 3298

getConnection returns a java.sql.Connection, your if statement should be using the isValid method of that to see if it's connected so for example that line could be if (conn.isValid(5)) { (where 5 is the maximum number of seconds to wait)

Upvotes: 0

Related Questions