Problem with return statement - java

I have problem with return statment >.< I want to store all magazine names into
ArrayList<String> ListNameMagazine = new ArrayList<String>();
I have a DB; in the DB there is a table name_magazine and the data in name_magazine is
Magazine1
Magazine2
Magazine3
Magazine4
This my main:
ShowData Show = new ShowData();
int HowManyMagazine = Show.HowManyMagazine(1); // to make sure there is how many Magazine name in my database
//System.out.print(HowManyMagazine); //i want to make sure the data is out.
String nmeMagazine = null; // this variable for get data from return statement
// i want to store in ListNameMagazine
ArrayList<String> ListNameMagazine = new ArrayList<String>();
for (int numbeer = 0;numbeer <= HowManyMagazine ; numbeer++)
{
//Store in 1 variable String, because if arrayList it's error
nmeMagazine = Show.getResult("Select Name_Magazine from Magazine");
// Store again in array list
ListNameMagazine.add(nmeMagazine);
}
for (String s : ListNameMagazine)
{
System.out.println(s); // show the data
}
This is my return statement:
public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
//String just_try = null;
while (rs.next()) {
System.out.println("Result:"+rs.getString(1));
//just_try = rs.getString(1);
//return just_try;
}
return null; //return just_try;
}
The problem is in return statement.
When the comment ( // ) I erase and the last return null; I delete. It become like here:
public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
String just_try = null;
while (rs.next()) {
//System.out.println("Result:"+rs.getString(1));
just_try = rs.getString(1);
return just_try;
}
return just_try;
}
When I show the data using this statement.
for (String s : ListNameMagazine)
{
System.out.println(s); // show the data
}
the result only
Magazine4
Magazine4
Magazine4
Magazine4
#.# I have confuse where the miss #.#
but when I show data in return statement like this
public String getResult(String sql)
throws SQLException
{
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
String just_try = null;
while (rs.next()) {
System.out.println("Result:"+rs.getString(1));
//just_try = rs.getString(1);
//return just_try;
}
return null;
}
The data show what I want. I know I only miss in somewhere but I don't know where that #.#. I hope you guys can found it .THX

Your problem is that return returns only one thing, and it will return immediately and the function will exit! You are retuning the name of a magazine just_try.
while (rs.next()) {
//System.out.println("Result:"+rs.getString(1));
just_try = rs.getString(1);
return just_try;
}
So, you start iterating through rs, and you get the name:
just_try = rs.getString(1);
And then you tell the code to return just_try.
return just_try;
At this point just_try will be returned and the function will exit! I think your problem is that you are expecting the function to keep going, and to keep returning values to the code that calls it, but this is not the way it works.
I suspect what you want to do is something like this:
ArrayList<String> ListNameMagazine;
ListNameMagazine = Show.getResult("Select Name_Magazine from Magazine");
then in the function getResult:
public ArrayList<String> getResult(String sql) throws SQLException {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData resultsetmetadata = rs.getMetaData();
ArrayList<String> returnArrayList = new ArrayList<String>();
while (rs.next()) {
returnArrayList.add(rs.getString(1));
}
return returnArrayList;
}

xan: Your method returns a String, while you try to return a list.
The signature must be changed to
public List<String> getResult(String sql) throws SQLException;

Related

How to use Resultset?

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.

Iterate 2D array of ResultSet to JTable

I have a resultset class that all of the query operations are stored. My problem is thatI am trying to fill a jtable with resultset data but I am only able to display the data in one column where I have three. This is the snippet of the resultset class:
public static List<List<String>> getAllFabrics() throws SQLException{
sql = "SELECT * FROM fabric";
List<List<String>> values = new ArrayList<>();
List<String> id = new ArrayList<>();
List<String> item = new ArrayList<>();
List<String> supplier = new ArrayList<>();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
//metaData = rs.getMetaData();
//int columnNum = metaData.getColumnCount();
while(rs.next()){
id.add(String.valueOf(rs.getInt("id")));
item.add(rs.getString("ItemDesc"));
supplier.add(rs.getString("Supplier"));
}
values.add(id);
values.add(item);
values.add(supplier);
return values;
}
and this is the jtable method that I am trying for hours to solve:
public static DefaultTableModel loadTable(){
ModelDB model = null;
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("Fabric");
tableModel.addColumn("Supplier");
try{
List<String> id = model.getAllFabrics().get(0);
List<String> item = model.getAllFabrics().get(1);
List<String> supplier = model.getAllFabrics().get(2);
//System.out.println(model.getAllFabrics().size()); tableModel.addRow(new Object[]{subRow});
for(List<String> row:model.getAllFabrics()){
tableModel.addRow(new Object[]{id,item,supplier});
}
}catch(SQLException ex){
ex.printStackTrace();
}
return tableModel;
}
I can't find a way to iterate the values to display in their respective column.
Original answer
You are almost there! You only need to change the loop:
for(int i = 0; i < id.size(); i++) {
tableModel.addRow(new Object[] {id.get(i),item.get(i),supplier.get(i)});
}
But as said in the comments, you should consider changing to an array of rows, not columns.
Edit
This is one approach. It is basically same as your code except the rows/columns are interchanged so the method returns a List of rows, not columns:
public static List<List<String>> getAllFabrics() throws SQLException{
sql = "SELECT * FROM fabric";
List<List<String>> values = new ArrayList<>();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
List<String> row = new ArrayList<>();
row.add(String.valueOf(rs.getInt("id")));
row.add(rs.getString("ItemDesc"));
row.add(rs.getString("Supplier"));
// Now row contains {id, item, supplier}
values.add(row);
}
return values;
}
Then in your loadTable() method change to:
...
try{
for(List<String> row: model.getAllFabrics()){
tableModel.addRow(row.toArray(new String[row.size()]);
}
...
In your original code you call model.getAllFabrics() multiple times to get the return value. This is not good because every time you do that the method gets called and it needs to make the SQL-request again etc. Store the return value in a variable instead. In this case though as the return value is only accessed once you can equally just do as I described above.
Hope this helps :)

How to return multiple rows from result set in java?

I have a query, which returns multiple rows to result set. now i need to return total rows in to the application which calling this function.
I tried with this code:
final PreparedStatement ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
result = rs.getInt(1);
}
by this code i am able to return only one value.
Now i want to return multiple rows
Create ArrayList of Integer and add result, return that array list.
ArrayList<Integer> resultList = new ArrayList<Integer>();
while (rs.next()) {
result = rs.getInt(1);
resultList.add(result);
}
return resultList;
You can use below code :
public static List<String> getSqlQueryResult(String sqlQuery) {
List<String> lst = new ArrayList<String>();
try {
Statement stmt = conSql.createStatement();
ResultSet res = stmt.executeQuery(sqlQuery);
ResultSetMetaData rsmd = res.getMetaData();
while (res.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
lst.add(res.getString(i));
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lst;
}
Try This code Hope this helps you
final PreparedStatement ps = con.prepareStatement(query);
ResultSet rs=ps.getResutlSet();
ResultSetMetaData rsmd=rs.getMetaData();
for(int i=1;i<=rsmd.getRowCount();i++){
String resut=rsmd.getString(i);
}
In this line result = rs.getInt(1); result is getting replaced each time with a new value.
A good alternate would be to store the values in a list then return the list provided the method return type should be List
Result set will contain the number of rows returned by the query.
Using result set object.next we can easily go through this rows of data.
In the above code you have only getting one value.
if result set contain more than one value.
then get this values using the index.
while(rs. next)
{
result1=rs.getInt(1);//this will get the two value in each row.
result2=rs.getInt(2);
}
if there are are more than one value then use that much index rs.getint(1)....rs.getInt(10)
also for Strings rs.getString(2)

ResultSet is closed. Why?

I've got a small problem. I launch my application and after launching a query and comparing rs == null I get error ResultSet is closed.
Here is the code:
error_code = NO_ERROR;
try
{
ArrayList <Harmonogram> al = new ArrayList <Harmonogram> ();
ResultSet rs = stat.executeQuery(myQuery);
if (rs == null)
{
return null;
}else{
Harmonogram harm = new Harmonogram(rs.getLong(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getLong(5), rs.getString(6));
After this I get a SQLException telling me: ResultSet is closed.
You are using incorrect method of checking whether ResultSet has any data.
Instead of
if ( rs == null )
{
return null;
}
use
if ( ! rs.next( ) )
{
return null;
}
The javadoc for PreparedStatement.executeQuery() says:
"Returns: a ResultSet object that contains the data produced by the query; never null"
The correct way to test for an empty ResultSet is to call ResultSet.hasNext().
Here's how I'd recommend that you write it:
public class HarmonogramDaoImpl implements HarmonogramDao {
private static final String FIND_ALL_SQL = "SELECT * FROM HARMONOGRAM ";
// inject this with either a constructor or setter
private Connection connection;
public List<Harmonogram> findAllHarmonograms() throws SQLException {
List<Harmonogram> harmonograms = new ArrayList<Harmonogram>();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = this.connection.prepareStatement(FIND_ALL_SQL);
rs = ps.executeQuery();
while (rs.hasNext()) {
Harmonogram harm = new Harmonogram(rs.getLong(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getLong(5), rs.getString(6));
harmonograms.add(harm);
}
} finally {
close(rs);
close(ps);
}
return harmonograms;
}
}
There are a few things left for you to do or guess, but this is a good start.
I would do something like
error_code = NO_ERROR;
try
{
ArrayList <Harmonogram> al = new ArrayList <Harmonogram> ();
ResultSet rs = stat.executeQuery(myQuery);
if (rs.next()){
Harmonogram harm = new Harmonogram(rs.getLong(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getLong(5), rs.getString(6));
}else{
return null;
}
}Catch...
Or even while(rs.next()) if you're trying to loop over the resultSet (get all the records pulled from the database)

How to find out if a Java ResultSet obtained is empty?

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
}`

Categories

Resources