I have writted a Java program that will be able to add customers to a database, and then look them up via a username or customer_id.
I am able to add users to the database without issue. Also, I am able to select a user by username or customer_id and print the user information into a JTextArea for viewing. What I would like to do, however, is print the user information from each specific column in their row of the database to the corresponding JTextField on my form. I think I need to use an array to do so, but I have had no success thus far.
The code I have at this point to select data is as follows:
public String selectCustomer() throws ClassNotFoundException, SQLException{
String result = "";
String strSQL = "SELECT * FROM customer WHERE username = '" + this.getUsername() + "'";
DataAccess DA = new DataAccess();
ResultSet rs;
try{
rs = DA.getResultSet(strSQL);
ResultSetMetaData metaData = rs.getMetaData();
int columns=metaData.getColumnCount();
while(rs.next()){//reading one record
for(int i=1;i<=columns;++i) {//this reads column by column
result+="<"+metaData.getColumnName(i)+">";
result+=rs.getString(i);
result+="</"+metaData.getColumnName(i)+">\n";
}//closes for loop
}//closes while loop
}//closes try
catch(SQLException sqle){sqle.printStackTrace();}
catch(Exception e){e.printStackTrace();}
return result;
}
Now I need to alter that code to place my column results into an array, and then I should be able to simply pull the data from the array, correct? I could be completely off my rocker here. I don't know. D:
Any advice would be appreciated.
Thanks!
Sure, you can get the values from the ResultSet using getString (and other getXXX methods) and then use setText to put the values into your text field.
This tutorial may help: http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
PS I forgot to say, you can get the values by column name rather than column index if you like - this is slightly slower but makes the code easier to write and maintain.
HTH