I make a query in my database and put the results in a resultset. I have 8 attributes in the resultset, and first 7 of them are strings, so i can take them by writing:
rs.getString(1), rs.getString(2) ... etc
Then at the index 8, i have an ArrayList. I try to take it and create new list with the values in it but i could not do it. Here is my code, you can see what i tried there in the commented out line:
public void loginCheck() {
try {
Bank bank = Bank.getBank();
ResultSet rs = queryDatabase();
if (rs.next()) {
// List<Account> a = (List<Account>) rs.getObject(8, ArrayList); DOES NOT WORK
Customer currentCustomer = new Customer(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7));
addToSession(currentCustomer);
rs.close();
DBConnect.disconnect(con);
FacesContext.getCurrentInstance().getExternalContext().redirect("main.xhtml");
} else {
rs.close();
DBConnect.disconnect(con);
}
} catch (SQLException | IOException e) {
}
}
private ResultSet queryDatabase() {
con = DBConnect.connect();
try {
PreparedStatement checkDB = (PreparedStatement) con.prepareStatement("SELECT * FROM users where identityNumber = ? AND password = ?");
checkDB.setString(1, identityNumber);
checkDB.setString(2, password);
ResultSet res=(ResultSet) checkDB.executeQuery();
return res;
} catch (Exception e) {
return null;
}
}
Edit: I have a Customer object with 8 attributes, first 7 of them are string and the last one is an ArrayList object. My resultset rs contains a Customer object, so i want to get this list from the resultset, i mean the accounts of this specific user
So how can i get this ArrayList in the resultset? Can anyone help?
Thanks
In your commented code you are missing .class, it should be:
List<Account> a = (List<Account>) rs.getObject(8, ArrayList.class);
Related
Why is my following code:
PrintWriter pw = response.getWriter();
pw.println(getValueOf(SQL, "lastName");
not printing anything after passing it into my method:
public static String getValueOf(String sql, String colName)
{
String result = "";
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
result = rs.getString(colName);
conn.close();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
In other words, why does it seem to be skipping the "try" clause entirely and just jumping to return the empty "" result at the end?
My SQL statment:
String SQL = "SELECT lastName FROM customers WHERE firstName=\"Bob\";";
I do have an entry for the person "Bob" (his lastname is "Mike") in my Customers table.
My Customers Table:
lastName / firstName / address / email
EDIT
It works correctly if I change the return type to "void" but I actually need a String value.
Alternate code:
public static void getValueOf(String sql, String colName, PrintWriter pw)
{
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
pw.println(rs.getString(colName)); // This does print out to the webpage as "Mike"
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Based upon your last edit, I would guess that you have more than one records.
So change your code to
if (rs.next()) {
result = rs.getString(colName);
}
And also, your code does not skip that try block
I am trying to read ref cursors, which returns only one column, a list of string data.
How can I do it java? Do I have to iterate through each resultset or is there any way so that I could get the entire column in one go. I have 5 ref cursor from the procedure.
rs1= (ResultSet) callableStatement.getObject(1);
rs2= (ResultSet) callableStatement.getObject(2);
rs3= (ResultSet) callableStatement.getObject(3);
while(rs1.next()){
list1.add(rs1.getString(1));
}
while(rs2.next()){
list2.add(rs2.getString(1));
}
while(rs3.next()){
list3.add(rs3.getString(1));
}
May this can help :
ResultSet result=null ;
PreparedStatement pstmt = null;
ArrayList yourlist = new ArrayList();
try
{
String queryString = "select yourfield from ....";
result = pstmt.executeQuery();
while(result.next())
{
yourlist.add(result.getInt("yourfield")); //if you are returning varchar so use getString
}
}
catch (SQLException e){
System.out.println("Exception: " + e.toString() );
}
finally
{
if(result!=null)
result.close();
if(pstmt!=null)
pstmt.close();
}
I wrote some java code to display database, when I run the code it gives me just the last element of database , but I wanna display all elements of table
the code :
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
What should I do? Can anyone please help me to display all values?
Thank you for helping me.
I think the problem is with your code that the value of puissance is overwritten every time you get the next element. Only the last value is returned. You should put the results into a list and return the whole list:
public List<String> RecupererPuissance() {
List<String> puissances = new ArrayList<String>();
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
puissance = rs.getString("Power");
puissances.add(puissance);
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissances;
}
public String RecupererPuissance() {
try {
Connection con = myDbvoiture.getConnection();
String queryPattern ="select Power from bd_voiture";
PreparedStatement pstmt = con.prepareStatement(queryPattern);
ResultSet rs = pstmt.executeQuery();
rs.first();
int count=0;
while (rs.next()) {
System.out.println("count = "+count);
count+=1;
puissance=rs.getString("Power");
System.out.println(puissance);
}
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return puissance;
}
If you see count printed only 1 time :
it would mean that you have only 1 row in column Power
and you maybe referring to the wrong column in your code
I am building an application in which you can save deals to database. I'd like to search deals in my database and populate my jtable with relevant results. I want to query my database on keyrelease event. I know it is not an efficient method but I am curious why I can't get it to work.
Below is a sample code that tries to query a database table with ID and country names. There are only 3 country names that start with "D". Somehow I can get country names printed out but can't get them to populate jtable.
The error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" I can't get ResultSet rs1 into a Object[][] . It works fine if I do System.out.println(rs1.getString("Name")
Below is the code -
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String columnName[] = new String[] { "Name" };
Object oss[][] = new Object[3][];
ResultSet rs1 = null;
int li = 0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection con = DriverManager.getConnection(Url, User, Password);
Statement st = con.createStatement();
String query = "SELECT * from unit.cntry WHERE Name LIKE '" + abc.getText() + "%';";
rs1 = st.executeQuery(query);
} catch (Exception e) {}
try {
while (rs1.next()) {
oss[li][0] = rs1.getString("Name");
li++;
}
myTable.setModel(new DefaultTableModel(oss, columnName));
} catch (SQLException ex) {
System.out.println(ex.toString());
} finally {
try {
if (rs1 != null) rs1.close();
} catch (SQLException e) {}
}
}
oss[li] = new Object[1];
oss[li][0] = rs1.getString("Name");
Other data structures might be more appealing.
Class.forName("org.sqlite.JDBC");
Connection conn =
DriverManager.getConnection("jdbc:sqlite:userdata.db");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");
int rowcount = rs.getRow();
System.out.println("Row count = "+rowcount); // output 1
rs.first(); // This statement generates an exception
Why is it so?
The pattern I normally use is as follows:
boolean empty = true;
while( rs.next() ) {
// ResultSet processing here
empty = false;
}
if( empty ) {
// Empty result set
}
Here's a simple method to do it:
public static boolean isResultSetEmpty(ResultSet resultSet) {
return !resultSet.first();
}
Caveats
This moves the cursor to the beginning. But if you just want to test whether it's empty, you probably haven't done anything with it yet anyways.
Alternatively
Use the first() method immediately, before doing any processing.
ResultSet rs = stat.executeQuery("SELECT * from table WHERE is_query_processed = 0;");
if(rs.first()) {
// there's stuff to do
} else {
// rs was empty
}
References
ResultSet (Java Platform SE 6)
You can do this too:
rs.last();
int numberOfRows = rs.getRow();
if(numberOfRows) {
rs.beforeFirst();
while(rs.next()) {
...
}
}
while (results.next())
is used to iterate over a result set.so results.next() will return false if its empty.
Why is execution not entering the
while loop?
If your ResultSet is empty the rs.next() method returns false and the body of the while loop isn't entered regardless to the rownumber (not count) rs.getRow() returns. Colins example works.
Shifting the cursor forth and back to determine the amount of rows is not the normal JDBC practice. The normal JDBC practice is to map the ResultSet to a List of value objects each representing a table row entity and then just use the List methods to determine if there are any rows.
For example:
List<User> users = userDAO.list();
if (users.isEmpty()) {
// It is empty!
if (users.size() == 1) {
// It has only one row!
} else {
// It has more than one row!
}
where the list() method look like as follows:
public List<User> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<User> users = new ArrayList<User>();
try {
connection = database.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(SQL_LIST);
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getLong("id"));
user.setName(resultSet.getString("name"));
// ...
users.add(user);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return users;
}
Also see this answer for other JDBC examples.
CLOSE_CURSORS_AT_COMMIT
public static final int CLOSE_CURSORS_AT_COMMIT
The constant indicating that ResultSet objects should be closed when the method Connection.commit is called.
Try with this:
ResultSet MyResult = null;
MyResult = Conexion.createStatement().executeQuery("Your Query Here!!!");
MyResult.last();
int NumResut = MyResult.getRow();MyResult.beforeFirst();
//Follow with your other operations....
This manner you'll be able work normally.
This checks if it's empty or not while not skipping the first record
if (rs.first()) {
do {
// ResultSet is not empty, Iterate over it
} while (rs.next());
} else {
// ResultSet is empty
}
May be you can convert your resultset object into String object and check whether is it empty or not.
`if(resultset.toString().isEmpty()){
// containg null result
}
else{
//This conains the result you want
}`