Im trying to return all the id from authors Table... but isnt working... Just returning me the first ID... But if i delete the return and put to Print, that give me all IDs..
String url = "jdbc:postgresql://localhost/testdb";
String user = "test";
String password = "test*";
try {
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT id FROM authors");
rs = pst.executeQuery();
while (rs.next()) {
return rs.getInt(1);
}
The return statement by default returns the value of the returned constant/variable, stops the method execution and leave the method. This is explained here: Returning a Value from a Method
To return all the results from the execution of your query, you must store the results in a List and then return this list:
List<Integer> idList = new ArrayList<Integer>();
//accessing to the database and executing the query...
rs = pst.executeQuery();
while (rs.next()) {
//store the ids in the list
idList.add(rs.getInt(1));
}
//close all the resources...
//at the bottom of your method
return idList;
Return play the role of break in this case , i suggest to return ResultSet and iterate over it using for or iterator in the View.
while (rs.next()) {
return rs;
}
And in the view:
while (nameOfYourFunction().next()) {
System.Out.println( rs);
}
return terminates your method call, as it denotes that this is the value, that the method was supposed to compute. Only the first return call in your method will ever get executed. So if you are planning on getting all the results from your query, you should return a collection of all those ids, which you construct before calling return with it.
Related
I am using a mysql table, and now I need to compare a columns all values with a given String.
I want to check if all values of the result set matches with encryptedString.
Need to understand what result set does and how it works.
Here I have a method, Some variables, and 2 mysql queries.
final String secretKey = "!!!!";
String name = jText.getText();
String pass = jTextPass.getText();
String originalString = pass;
String encryptedString = AES.encrypt(originalString, secretKey) ;
String decryptedString = AES.decrypt(encryptedString, secretKey) ;
PreparedStatement PS;
ResultSet result;
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` =?";
PreparedStatement ps;
String query;
query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`=?";
try {
PS = MyConnection.getConnection().prepareStatement(query1);
PS.setString(1, name);
PS.setString(2, encryptedString);
rs = PS.executeQuery();
//while(result.next() ){
//I am not understanding what to do here.
ps = MyConnection.getConnection().prepareStatement(query);
ps.setString(1, encryptedString);
ps.setString(2, name);
ps.executeUpdate();
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
this.dispose();
//}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
}
First tip: using try-with-resources closes statement and result set even on exception or return. This also reduces the number of variable names for them because of the smaller scopes. This return from the innermost block I utilized. For unique names one can use if-next instead of while-next. A fail-fast by not just logging the exception is indeed also better; you can exchange the checked exception with a runtime exception as below, so it easier on coding.
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` = ?";
String query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`= ?";
try (PreparedStatement selectPS = MyConnection.getConnection().prepareStatement(query1)) {}
selectPS.setString(1, name);
//selectPS.setString(2, encryptedString);
try (ResultSet rs = selectPS.executeQuery()) {}
if (result.next()){ // Assuming `name` is unique.
String pass = rs.getString(1);
try (PreparedStatement ps = MyConnection.getConnection().prepareStatement(query)) {
ps.setString(1, encryptedString);
ps.setString(2, name);
int updateCount = ps.executeUpdate();
if (updateCount == 1) {
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
return success;
}
}
}
}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalStateException(e);
} finally {
dispose();
}
the ResultSet object contains all the information about the query that you perform, it will contain all columns. In your code the result variable will return anything since there is no part in your code where is executed, to do this you have to...
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
while(result.next()){
String column1 = result.getString("columnName");
}
The result.next() method is a boolean method that says if the ResultSet object still have values of the table inside and it will continue until it reaches the last row that your SELECT statement retrives. Now if you want to match the value of some column with other variables you can do it inside the while(result.next()).
result.getString("columnName") will extract the value from columnName as a String.
If you want to save things in an ArrayList to save the data and then use this list as you want the code can be like...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
List<Object> data = new ArrayList();
while(result.next()){
data.add(result.getString("columnName"));
}
return data;
Obviously you have to change the Object with the type of things that you want to store in the List.
Or if you want to store the data in an array. As I said in my comment this won't be dinamic, but...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
String[] data = new String[NUMBER_OF_COLUMNS_IN_RESULTSET];
while(result.next()){
data[0] = result.getString("columnName1");
data[1] = result.getString("columnName2");
data[2] = result.getString("columnName3");
//And so on...
}
return data;
The other way is that if you are returning an entity you can set the values of the ResultSet directly in the POJO:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
Entity entity = new Entity();
while(result.next()){
entity.setColumnName1(result.getString("columnName1"));
entity.setColumnName2(result.getString("columnName2"));
entity.setColumnName3(result.getString("columnName3"));
//And so on...
}
return entity;
There are so many ways to store the data, just ask yourself how do you want to receive the data in the other parts of you code.
Regards.
I have a SQLite database and there is one record with id=2. I am able to login but can't set the id_from_table value(Class variable) value to it's value from table. It is 0 always .Why is this happening? What am I doing wrong here? I can login though ! Help appreciated ,thanks .
database ;
public boolean login(String userid, String userpass) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM user WHERE username = ? AND passkey = ?";
try{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,userid);
preparedStatement.setString(2,userpass);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
id_from_table = resultSet.getInt("id"); //not working-when retrieved in another class it shows 0
return true;
}
else {
// System.out.println(resultSet.next());
return false;
}
}
catch (SQLException e){
e.printStackTrace();
}
finally {
preparedStatement.close();
resultSet.close();
}
return false;
}
I found my own way around.
It retrieved value from database but since my variable wasn't public static I couldn't access without creating a object (First I did after creating object). And Class I was using for accessing was LoginModel but it was supposed to be Controller in which my login method was written.
So Controller.id_from_table worked. I defined id_from_table in Controller and assigned value before login(username,passkey) method ends.
When I carry out the following operations:
public Product getProductById(long productId) throws DaoException {
Connection con = DBManager.connect();
PreparedStatement statement = null;
ResultSet rs = null;
try {
statement = con.prepareStatement(QUERY_PROD_BY_ID);
statement.setLong(1, productId);
rs = statement.executeQuery();
//rs.first();
Product product = new Product();
product.setProductId(rs.getLong("product_id"));
product.setProductImage(rs.getString("image"));
product.setProductBrand(rs.getString("brand"));
product.setProductModel(rs.getString("model_no"));
product.setProductPrice(rs.getFloat("price"));
product.setProductSummary(rs.getString("summary"));
product.setProductStock(rs.getInt("stock"));
product.setProductCategory(rs.getLong("category_id"));
product.setProductCreationTime(rs
.getTimestamp("product_creation_time"));
product.setProductStatus(ProductStatusState.values()[rs
.getInt("product_status")]);
product.setType(ProductType.values()[rs.getInt("type")]);
return product;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
DBManager.closeAll(statement, rs);
}
}
I get an error which says
org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.
My ProductId is my primary key and hence only one row will be present in the ResultSet. When I set a
while(rs.next){...}
it returns me null. What should I do?
As stated in previous comments, when you execute a query that returns a result set the initial position of the cursor is before the first row of data in the result set. Calling rs.next() will move your cursor to your first row and allow you to access the data that was returned with the rs.getXXX() methods.
I would like to see only that products user is looking for them, but when second if is executed it will push(pointer or whatever is there) to next ID(id I have as unique so it will push to nowhere) and result is null. I hope you understand my problem :).
if (stmt.execute(
"SELECT * FROM products where ID=" + removeName)) {
rs = stmt.getResultSet();
if (!rs.next()) {
m = "ID not found.";
return m;
}
In your case, you can go for PreparedStatement for avoiding SQL-Injection problem.
PreparedStatement prodsQuery= con.prepareStatement("SELECT * FROM products where ID=?");
prodsQuery.setInt(1,removeName);
ResultSet rs = prodsQuery.executeQuery();
if(!rs.next())
{
m = "ID not found.";
return m;
}
The problem is that you're reading the first result in order to know if there's at least one result, then trying to consume the next results and missing the first one (adapted from your question description). I gave an explanation of how this works here.
A possible solution for this problem would be assuming the query executed with no problems and you have your results, then retrieve the data (or List of data) and as a last step verify if the data is not null or the List of data is not empty.
Code adapted from Naveen's answer to show the proposed solution
PreparedStatement prodsQuery =
con.prepareStatement("SELECT * FROM products where ID=?");
prodsQuery.setInt(1,removeName);
ResultSet rs = prodsQuery.executeQuery();
Assuming there's only one result to get:
//also assuming you will set the results in a Data class (yes, this can be replaced)
Data data = null;
if (rs.next()) {
//logic to retrieve data...
data = new Data();
data.setSomething(rs.get(1));
//more and more code to fill the data...
//because it looks that you need it as String (wonder why you return a String as well)
return data.toString();
}
//note: I use an else statement to check if indeed there were no results at all
//else statement added using a line separator for code explanation purposes
else {
m = "ID not found.";
return m;
}
Assuming there is a list of results to get:
//also assuming you will set the results in a Data class (yes, this can be replaced)
List<Data> dataList = new ArrayList<Data>();
while (rs.next()) {
//logic to retrieve data...
Data data = new Data();
data.setSomething(rs.get(1));
//more and more code to fill the data...
//because it looks that you need it as String (wonder why you return a String as well)
dataList.add(data);
}
//in this case, there's no validation in order to know if there's any result
//the validation must be in the client of this class and method checking if
//the result list is empty using if(!List#isEmpty) { some logic... }
return dataList;
First thing, your approach is vulnerable to SQL Injection. Please go for PreparedStatement.
Look at this simple example for using PreparedStatement
And you should do like this :
ResultSet rs = stmt.executeQuery("SELECT * FROM products where ID=" + removeName);
if (!rs.next()) {
m = "ID not found.";
return m;
}
public ResultObject takePrefixGroupId(ArrayList prefixGroupName)
{
debugLog(MODULE_NAME, "Inside the takePrefixGroupId() of LCRConfigurationSessionBean");
ResultObject resultObject = new ResultObject(LCRResponseCode.LCR_CONFIGURE_SEARCH_ERROR_EJB, null);
String strSelectQuery = null;
String strMessage=null;
ResultSet resSet = null;
Collection colInValideRecord =new ArrayList();
Collection colErrorMessage=new ArrayList();
Collection colValidRecord = new ArrayList();
Collection colDataValidation=null;
try{
for(int i=0;i<prefixGroupName.size();i++)
{
strSelectQuery = "select DESTINATIONGROUPID from TBLMDESTINATIONGROUP where NAME='"+prefixGroupName.get(i)+"'";
debugLog(MODULE_NAME, "Query::::::"+strSelectQuery);
resultObject = execute(strSelectQuery);
if(resultObject.getResponseCode() == LCRResponseCode.SUCCESS_RESPONSE_CODE)
{
resSet = (ResultSet)resultObject.getResponseObject();
debugLog(MODULE_NAME, "resSet::::::"+resSet);
if(resSet != null)
{
while(resSet.next())
{
colValidRecord.add(resSet.getString("DESTINATIONGROUPID"));
}
}
else
{
strMessage=LCRResponseCode.errorCodeToMessage(LCRResponseCode.PREFIX_GROUP_DOES_NOT_EXIST_ERROR);
debugLog(MODULE_NAME,"MESSAGE::: "+strMessage);
colErrorMessage.add(strMessage);
colInValideRecord.add(prefixGroupName);
debugLog(MODULE_NAME,"No Prefix Group is found.");
}
colDataValidation=new ArrayList();
colDataValidation.add(colValidRecord);
colDataValidation.add(colInValideRecord);
colDataValidation.add(colErrorMessage);
resultObject.setResponseObject(colDataValidation);
resultObject.setResponseCode(LCRResponseCode.SUCCESS_RESPONSE_CODE);
}
else
{
debugLog(MODULE_NAME, "Unable to execute search query for in searchDestination() of LCRConfigurationSessionBean.");
resultObject.setResponseCode(LCRResponseCode.LCR_CONFIGURE_SEARCH_ERROR_EJB);
}
}
}
catch(Exception e)
{
e.printStackTrace();
errorLog(MODULE_NAME, "exception in searchDestination() of LCRConfigurationSessionBean");
resultObject.setResponseCode(LCRResponseCode.LCR_CONFIGURE_SEARCH_ERROR_EJB);
resultObject.setException(e);
}
return resultObject;
}
this is the code
According to the javadoc, Statement.executeQuery() never returns null. So the answer is a ResultSet with no rows.
You can tell that the ResultSet is empty if next() returns false the first time you call it.
You may also be able to tell by calling the optional isAfterLast() method. If it is supported, this method will give you an answer without advancing the cursor as a side-effect.
I've no idea what the answer would be for your code, since you are calling an execute method whose implementation you have not provided.
ResultSet executeQuery(String sql)
throws SQLException Executes the given SQL
statement, which returns a single
ResultSet object.
Parameters: sql - an SQL statement to be sent to the database, typically
a static SQL SELECT statement
Returns: a ResultSet object that contains the data produced by the
given query; never null
Throws: SQLException - if a database access error occurs, this
method is called on a closed Statement
or the given SQL statement produces
anything other than a single ResultSet
object
Statement
Also you can do it like:
if(resSet.last().getRow() > 0)
{
resSet.first();
while(resSet.next())
{
colValidRecord.add(resSet.getString("DESTINATIONGROUPID"));
}
}
else
{
//...