Update your TestPersistence.java to retrieve all the entries in the users table, lke this:
package org.confucius;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
public class TestPersistence {
public static void main(String[] args) {
MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
dataSource.setUser("confucius");
dataSource.setPassword("changeit");
dataSource.setServerName("localhost");
dataSource.setPort(3306);
dataSource.setDatabaseName("confuciusDB");
try {
Connection conn = dataSource.getConnection();
String sqlQuery = "select firstName,lastName from users";
PreparedStatement ps = conn.prepareStatement(sqlQuery);
ResultSet rs = ps.executeQuery();
while (rs.next()){
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
System.out.println("Got User: " + firstName + " " + lastName);
}
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Executing the query returns a ResultSet.
We iterate over the ResultSet to get the query results.
R-click on the TestPersistence.java file in your Eclipse Navigator view.
Select Run As --> Java Application.
You will see the users printed to the console.
No comments:
Post a Comment