Maddy
Maddy

Reputation: 2060

Unable to retrieve first column

I am trying to get the first column (column id and get the associated first and last name). I have tried multiple things but unable to get it to work.

It returns me with error CUSTOMERID not found.

public String getCustomerUsingId(int id) {

String firstName = null;
String lastName = null;

Statement stmt = null;

String getCustomerQuery = "SELECT FIRSTNAME,LASTNAME FROM CUSTOMERS WHERE CUSTOMERID ='"
        + id + "'";

try {
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    stmt = conn.createStatement();
    stmt.execute(getCustomerQuery);
    ResultSet rs = stmt.getResultSet();
        if(rs.next()){
            id = rs.getInt("CUSTOMERID");
            System.out.println("id is:" + id);
            if(id == -1){
                System.out.println("value is true");
                firstName = rs.getString(2);
                lastName =  rs.getString(3);
                System.out.println("First Name :" + firstName);
                System.out.println("First Name :" + lastName);
            }
        }
    }

I am using H2 as database and this is what is looks like

CUSTOMERID      FIRSTNAME   LASTNAME  
1                P              S
2                K              S

This is how I have created the table

String customerSqlStatement = "CREATE TABLE CUSTOMERS " + "(customerId INTEGER NOT NULL IDENTITY(1,1) PRIMARY KEY, " + " FirstName VARCHAR(255), " + " LastName VARCHAR(255))";

Upvotes: 0

Views: 50

Answers (1)

kucing_terbang
kucing_terbang

Reputation: 5141

You also need to explicitly include the column name in the select query.

So, the variable getCustomerQuery should be something like

String getCustomerQuery = "SELECT CUSTOMERID,FIRSTNAME,LASTNAME FROM CUSTOMERS WHERE CUSTOMERID ='"
    + id + "'";

Upvotes: 2

Related Questions