Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum for use across class

I am having trouble declaring an enumeration for DB field types that I can use across all functions of a particular class. With the following code I get "cannot resolve USERNAME to a variable type":

public class SQL_access {

    public enum DBfields { BLANK, USERNAME, ID, PASSWORD, FIRSTNAME, LASTNAME }; 

    public boolean loginValidate( String username, String password ){

        String DBuser, DBpass;
        PreparedStatement table = connectToTable( "firstsql", "users");
        ResultSet row = table.executeQuery();;

        while(row.next()){
            DBuser = row.getString(USERNAME);
            if(DBuser.equals(username)){
                DBpass = row.getString(PASSWORD);
                break;
            }
        }
    }
};
like image 638
Austin Avatar asked Jul 26 '26 23:07

Austin


2 Answers

You need to use DBfields.USERNAME.

UPDATE:

in order to use with the getString(String) method, you need to use the name of the enum, like: Dbfields.USERNAME.name().

if you are using the enums only for the jdbc API access, you would be better off just using a String constant:

public static final String DBFIELD_USERNAME = "USERNAME";
like image 58
jtahlborn Avatar answered Jul 28 '26 14:07

jtahlborn


You need to reference the enum Type: DBfields.USERNAME, or statically import the enum like:

import static mypackage.SQL_access.DBfields.*;

Also, in your case, this is not enough. You need to pass the column name -- a String -- or the column position -- an int -- to the ResultSet:

row.getString(DBfields.USERNAME.name());

Used like this, you loose the main advantage of enums which is it's static nature, but it can still be useful in other places in your code if you refer to these values as a "bag".

like image 20
bruno conde Avatar answered Jul 28 '26 14:07

bruno conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!