How to check resultset is empty or null in java - java

I have a sql query to run in my java class (Servlet) what i am trying to do if there is no data in database for that query then want to do something else.
In simple terms i am checking if there is no data in resultset than want to do something else,but that's not working
What i have tried
String str = null;
Gson gson = new Gson();
LinkedHashMap<Object, Object> lhm = null;
LinkedList<LinkedHashMap<Object, Object>> mainList = new LinkedList<LinkedHashMap<Object, Object>>();
String sql;
try {
Connection con = DBConnection.createConnection();
Statement statement = con.createStatement();
sql = "select distinct a.DISPLAYCOUNTERNAME from DISPLAYCOUNTERNAMES a,DISPLAYCOUNTER b where a.DISPLAYCOUNTERCODE=b.DISPLAYCOUNTERCODE and USERNAME='"
+ userName + "'";
System.out.println(sql);
ResultSet resultSet = statement.executeQuery(sql);
if (!resultSet.isBeforeFirst()) { // if there is no data
lhm = new LinkedHashMap<Object, Object>();
lhm.put("outlet", "NoData");
mainList.add(lhm);
str = gson.toJson(mainList);
}
while (resultSet.next()) { // if there is data
lhm = new LinkedHashMap<Object, Object>();
counterName = resultSet.getString("DISPLAYCOUNTERNAME");
System.out.println("counternam"+counterName);
lhm.put("Counter name", counterName);
mainList.add(lhm);
str = gson.toJson(mainList);
}
System.out.println(str);
response.setContentType("application/json");
response.getWriter().write(str);
} catch (SQLException e) {
System.out.println("SQL Issues 2...");
e.printStackTrace();
}
The above code is throwing error as SQL Issues 2...
java.sql.SQLException: This method should only be called on ResultSet objects that are scrollable (type TYPE_SCROLL_INSENSITIVE).
I don't know what i am doing wrong here,any-kind of help will be appreciated

You can try modifying the line:
Statement statement = con.createStatement();
to
Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

You could use next but switch to use a do/while loop, if the first call to next returns true then the row pointer points to the first row in the result set so you must read it before calling next again
if (!resultSet.next()) {
// do no data stuff
} else {
do {
//handle result set data
} while (rs.next());
}

Related

Return a dynamic array based on SQL

I would like to create a method that returns an array with all the values from the database.
This is what I have so far:
package ch.test.zt;
import java.sql.*;
class Database {
static boolean getData(String sql) {
// Ensure we have mariadb Driver in classpath
try {
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mariadb://localhost:3306/zt_productions?user=root&password=test";
try {
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs.next();
}
catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
That means, I could use Database.getData("SELECT * FROM users") and I get an array with all the data from the database that I need.
In my code above I am using return rs.next();, which is definitely wrong. That returns true.
rs.next(); just tell whether your result set has data in it or not i.e true or false , in order to use or create array of the actual data , you have to iterate over your result set and create a user object from it and have to add that object in your users list
Also change the signature
static List<User> getData(String sql)
And best to use like Select Username,UserId from Users; as your sql
something like this:
try { List<User> userList = new ArrayLisy();
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
//until there are results in the resultset loop over it
while (rs.next()) {
User user = new User();
user.SetName(rs.getString("username"));
// so on.. for other fields like userID ,age , gender ,loginDate,isActive etc ..
userList.add(user);
}
}
when you don't know about the columns of the table you are going to fetch then you can find the same using :
Now you know all the information then you can construct a proper query using it
and work from this
DatabaseMetaData metadata = connection.getMetaData();
ResultSet resultSet = metadata.getColumns(null, null, "users", null);
while (resultSet.next()) {
String name = resultSet.getString("COLUMN_NAME");
String type = resultSet.getString("TYPE_NAME");
int size = resultSet.getInt("COLUMN_SIZE");
System.out.println("Column name: [" + name + "]; type: [" + type + "]; size: [" + size + "]");
}
}

Problem with diacritic, getting data from database java

I have MySQL database, where I have saved data and some words have diacritics.
This is my function how to get data from database.
public List<RowType> getData(String query){
List<RowType> list = new ArrayList<>();
try{
connect();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()){
StringBuilder str = new StringBuilder();
for(int i = 1; i <= getCountColumns(resultSet); i++){
if(i==1) str.append(resultSet.getString(i));
else str.append("," + resultSet.getString(i));
}
list.add(new RowType(str.toString()));
}
}
catch(Exception e){
System.out.println("Chyba při získavání údajů z databáze.");
System.out.println(e);
Console.print("Chyba při získavání údajů z databáze.");
Console.print(e.toString());
}
finally{
disconnect();
}
return list;
}
As parameter i send this query.
List<RowType> list = connection.getData("Select id from countries where name = 'Česko'");
But it doesn´t find anything, because i have diacritic in the query ("Česko"). I try it without diacritic and it works. So don´t you know how to fix it to work with accents too?
Can you try to add a few more queries before executing your main query?
so it will look something like:
connect();
Statement statement = connection.createStatement();
String query2 = "SET NAMES 'utf8'";
statement.execute(query2);
query2 = "SET CHARACTER SET 'utf8'";
statement.execute(query2);
ResultSet resultSet = statement.executeQuery(query);
if the above does not work for you, then maybe there is an issue with your database settings; if that's the case, you can refer to the answer here

How do I return multiple rows from a JDBC method?

I am currently learning JDBC and can successfully query and retrieve data from a MysQL database. But I would like to run this as a method and return the resultset rows from the method to the calling program.
So far I think I have made an appropriate method but am stuck returning the resultset as an object. Eclipse gives me the following error for the return type:
Object cannot be resolved to a type
Here is the method:
public object getAllPosts(int catID) throws Exception{
try{
this.catID = catID;
sql = "SELECT post_id, post_title, post_content, post_date FROM crm_posts WHERE cat_id = ? LIMIT ?";
prep = conn.prepareStatement(sql);
prep.setInt(1, catID);
prep.setInt(2, 3);
// execute statement
rs = prep.getResultSet();
} catch(Exception e){
e.printStackTrace();
}
return rs;
}
What is the return type I should use or is there a better way of doing this?
EDIT:
As stated in the comments it was a (annoying) typo. Object with a capital O.
If you're not going to return a ResultSet or Object object, then you should define your return type. You could create your own Post object for each row in the ResultSet, put those objects in a list, and return the list.
This is how you do it
public List<MyClassThatRepresentsTableInDatabase> getAllPosts(int catID) throws Exception{
try{
this.catID = catID;
sql = "SELECT post_id, post_title, post_content, post_date FROM crm_posts WHERE cat_id = ? LIMIT ?";
prep = conn.prepareStatement(sql);
prep.setInt(1, catID);
prep.setInt(2, 3);
// execute statement
rs = prep.getResultSet();
List<MyClassThatRepresentsTableInDatabase> ret=new ArrayList<>();
while(rs.hasNext()){
MyClassThatRepresentsTableInDatabase item=
new MyClassThatRepresentsTableInDatabase();
item.setId(rs.getLong("post_id");
item.setName(rs.getString("post_title");
item.setContentd("post_content");
//etc..
ret.add(item);
}
return ret;
} catch(Exception e){
e.printStackTrace();
}
return new ArrayList();
}
Excecute your query in ResultSet and loop it to get your results.
Use the following line of codes :
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
out.println(rs.getString("//Your Column name"));
}

Store rows of resultset in array of strings

I want to count the numbers of entries in resultset and then store these values in an array and pass this array to create a graph.
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename"); // this statement will select the unique entries in a
particular column provided by jtextfield
int count=0;
while(rs.next())
{ ++count; } // This will count the number of entries in the result set.
Now I want to store the values of result set in an array of string. I used the following code
String[] row = new String[count];
while(rs.next())
{
for (int i=0; i <columnCount ; i++)
{
row[i] = rs.getString(i + 1);
}
}
Error : Invalid Descriptor Index.
Please suggest how to copy the result of resultset in array.
For example if I enter priority in jTextField , the result set will contain
priority1
priority2
priority3
In your first while loop you read all the entries in the ResultSet, so when executing the second while loop there's nothing else to read. Also, the index of ResultSet#getXxx starts at 1, not at 0. Also, since you don't know the amount of rows that you will read, it will be better using a List backed by ArrayList instead.
Considering these, your code should look like:
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+
" as call from tablename");
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
Based in your comment, I extended the sample:
public List<String> yourRandomQuery(String columnName) {
Connection con = null;
ResultSet rs = null;
List<String> results = new ArrayList<String>();
try {
String baseQuery = "SELECT DISTINCT %s AS call FROM tablename";
con = ...; //retrieve your connection
ResultSet rs = stmt.executeQuery(String.format(baseQuery, columnName));
while(rs.next()) {
results.add(rs.getString(1));
}
} catch (SQLException e) {
//handle your exception
e.printStacktrace(System.out);
} finally {
closeResource(rs);
closeResource(con);
}
return results;
}
//both Connection and ResultSet interfaces extends from AutoCloseable interface
public void closeResource(AutoCloseable ac) {
try {
if (ac != null) {
ac.close();
}
} catch (Exception e) {
//handle this exception as well...
}
}
public void someMethod() {
//retrieve the results from database
List<String> results = yourRandomQuery(jTextField.getText());
//consume the results as you wish
//basic example: printing them in the console
for(String result : results) {
System.out.println(result);
}
}
Try this
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename");
List<String> list=new ArrayList<>();
while(rs.next())
{
list.add(rs.getString(1));
}
Why not just create a HashSet<String> and write into that. Note that HashSet is unordered, just like your query. By using a collection that is of arbitrary size you don't need to determine the require dsize in advance.

DB query not populating to combo box...why?

I've been at this for awhile and have tried different examples (including a few that I found here), and tried to adapt them to what I need.
I am trying to use a DB query in a servlet to populate a combo box in the resulting html form that is created. While it all compiles and the page pops up with a combobox, there is nothing in the box to choose from, which tells me that something is wrong with how I am passing variables.
I've basically narrowed my methods down to two, but get the same results from both.
Can someone have a look-see and give me a clue?
out.print(`"<tr><td>SoldWhich Home ID: `</td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
ArrayList<String> soldWhich = new ArrayList<String>();
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String[])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
And the other method:
out.print(`"<tr><td>SoldWhich Home ID: </td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try{
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home ORDER BY home_id";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
soldWhich.add(rs1.getString(1));
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String [])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
Where are you setting "home_id" request attribute and why are you even setting it? I think you should take out the following line of code and see if it works. Modify your code to this.
List<String> soldWhich = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
I think you are not actually getting values (sh) in the "for(String sh : soldWhich)" loop. Can you try printing the values in a simple table just to see if you actually get data? Also why aren't you using jstl to perform this task? And your catch block does not log any errors either in case you are actually getting some sort of errors that will go unnoticed.

Categories