Java SQL problem executing query through CallableStatement with parameter - java

I have a problem in a CallableStatement that execute a stored procedure query which accept a parameter.
I have a list of string that contains the query like:
{call query5_immatricolati(?)}
I have a list of string that contains the parameter like
String cds = "L-INF";
I have no SQL syntax error when I run but the result set doesn't have any value.
The expected result of the execution is that i could create an object by receiving data from the result set.
Here is the code:
for (int i = 0; i < INDICATORI.getInstance().getListaIndicatori().size();) {
for (int j = 0; j < INDICATORI.getInstance().getListaQuery().size();) {
if (INDICATORI.getInstance().getListaIndicatori().get(i).equals("iC00a")) {
for (String cds : CDS.getInstance().getCds().values()) {
ArrayList<indicatore> lista = new ArrayList<indicatore>();
String query = INDICATORI.getInstance().getListaQuery().get(j);
try {
CallableStatement cb = DB.getInstance().getConnection().prepareCall(query);
cb.setString(1, cds);
DB.getInstance().setResultSet(cb.executeQuery());
} catch (SQLException e) {
e.printStackTrace();
}
try {
while (DB.getInstance().getResultSet().next()) {
iC00a obj = new iC00a();
obj.setId(counter);
obj.setAnnoIscrizione(DB.getInstance().getResultSet().getString(1));
obj.setIscrittiPrimoAnno(DB.getInstance().getResultSet().getInt(2));
lista.add(obj);
counter++;
}
} catch (SQLException e) {
e.printStackTrace();
}
map.getInstance().getMap().put(INDICATORI.getInstance().getListaIndicatori().get(i)+cds, lista);
counter=0;
}
}
i++;
j++;
}
}
I tried to manually set in cb.setString(1,cds) the value like cb.setString(1,"L-INF") AND IT WORKS !!!
But I can't set manually the parameter, I need to iterate with for each loop each string and dynamically insert as parameter.
Why if I set the parameter manually like a string it works instead if i give a string variable not ?
Could anyone tell me what I'm doing wrong?

After a lot of attempts, I've found the solution.
The problem is in your variable cdsbecause it could have white spaces before or after.
Try:
cb.setString(1,cds.strip());
For me it worked.

Related

SQL Update in another class

Thanks for helping me out with my problem.
So I tried to insert a SQL Update using a method in a class named Functions, the main program doesn't give any error, and whenever I use the function, it just don't change anything in the SQL table after refreshing.
Here is my updateSQL method in class Functions :
public static void updateSQL(String sql, String updatenames[])
{
Connection connected = null;
PreparedStatement prepared = null;
connected = connexionmysql.connexionDB();
try
{
prepared = connected.prepareStatement(sql);
for(int i = 1; i < updatenames.length+1 ; i++) {
prepared.setString(i, updatenames[i-1]);
}
prepared.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
And here is how I call this function in my main class :
String datan[] = { inputPASS, type1, inputEMAIL, inputNAME };
Functions.updateSQL("UPDATE users SET userPASS = ? ,userTYPE = ? ,userEMAIL = ? WHERE userNAME = ? ", datan);
I did solve the problem. The functions I did write are working as expected, but the problem was in the way I was calling the method.
Instead of calling the function in a static way, I was calling it in an "usual" way so Eclipse didn't give me any error in that line.

Hibernate IN clause from a JSONArray

I am trying get a list with Hibernate. I get a JSONArray with the IN values.
JSONArray rolesEnSession is, for example, ["ROLE1", "ROLE2"]
public List<MenuLeft> getMenu(JSONArray rolesEnSession){
String listaRoles = "";
for (int i = 0; i < rolesEnSession.length(); i++) {
try {
listaRoles = listaRoles + "'"+rolesEnSession.getString(i)+",";
} catch (JSONException ex) {
Logger.getLogger(LinkDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
return getCurrentSession()
.createQuery("from MenuLeft "
+ "WHERE menuRol in (:rolesEnSession)")
.setParameter("rolesEnSession", listaRoles)
.list();
}
But I get a blank value. The column menuRol in database has values ROLE1 and ROLE2
Consider listaRoles after two iterations with your current code. It will have value:
'ROLE_1,'ROLE_2,
Instead of trying to build a well-formed string of parameter values, just change listaRoles to be an actual List and pass that in as a parameter. Let Hibernate handle the conversion to a valid SQL.

Mysql: Get Strings?

I try to receive all names out of my database.
I did write this code:
public static String getCmdCommand(int resultCount) throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
PreparedStatement zpst=null;
ResultSet zrs=null;
zpst=connect.prepareStatement("SELECT `befehlsname` FROM `eigenebenutzerbefehle`");
zrs=zpst.executeQuery();
if(zrs.next()){
return zrs.getString(resultCount);
}else{
return "-none-";
}
}catch (Exception e) {
throw e;
} finally {
close();
}
}
and i start the method by running a loop:
for(int i = 0; i <= cmdAmount-1; i++){
try {
eebBenutzerBefehl = dao.getCmdCommand(i);
} catch (Exception e) {
e.printStackTrace();
}
}
cmdAmount is a integer with the valuable of the total fields inside the database.
so i.e My database holds name1 name2 name3, is it wrong to call them like this? :
return zrs.getString(resultCount);
which should be:
zrs.getString(0) = name1
zrs.getString(1) = name2
zrs.getString(2) = name3
I always receive java.sql.SQLException: Column Index out of range, perhaps it just continue to check the first entry only in the database :confused:
return zrs.getString(resultCount);
The getString() method should be given the index of the column you want to return which is always going to be the same. You should pass in a constant here such as 0.
Also, you should open the database only once rather than over and over again in that one method by passing in the "connect" variable as a parameter.
Here's what I would do if you are wanting to retrieve the name from each row of the table.
public static ArrayList<String> getCmdCommand(Connection connect) throws Exception {
try {
PreparedStatement zpst=null;
ResultSet zrs=null;
ArrayList<String> names = new ArrayList<String>();
zpst=connect.prepareStatement("SELECT `befehlsname` FROM `eigenebenutzerbefehle`");
zrs=zpst.executeQuery();
// The result set contains all the names retrieved from the call to the database, so
// you just need to iterate through them all and store them in a list.
while(zrs.next()) {
names.add(zrs.getString(0));
}
} catch (Exception e) {
throw e;
} finally {
close();
}
return names;
}
You don't need to tell it how many fields there are because it will figure that out itself.
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
try {
ArrayList<String> names = dao.getCmdCommand(connect);
} catch (Exception e) {
e.printStackTrace();
}
if(names.size() < 1) {
// " - none - "
}

how to add a check in Java code for fetching only non-negative values from result-set

In my Java code I have embedded a SQL query which fetches data from a database and stores it in a result-set. I want to add a function or a piece of code which will take only non-negative data from the result-set for further processing.
Assumption: The result set can contain positive/negative/zero data values as well as characters. Also i cannot change the SQL query as its out of my scope.
try something like this, i think it will do the job
private ArrayList getNegativeNumbers(ResultSet rs, String coulumnName ) throws SQLException
{
ArrayList ret = new ArrayList();
while(rs.next()){
try {
int x = rs.getInt(coulumnName);
if(x>=0){
ret.add(new Integer(x));
}
} catch (Exception ex) {
String x = rs.getString(coulumnName);
ret.add(x);
}
}
return ret;
}
UPDATED 2. Sorry for my edits, i missread the question
while (resultSet.next()) {
if(resultSet.getInt("Column name") > 0);
Processmethod(resultSet.getInt("Column name") );
}

Why does the NetBeans Java debugger never reach this code?

I'm trying to debug a method in Java using NetBeans.
That method is:
public Integer getNumberOfClamps(Locations paLocation) {
Integer ret = -1;
List list = new ArrayList();
String removeme = "ABC";
if (paLocation == null) {
return ret;
}
try {
IO io = new IO(this.getSchemaName());
Session session = io.getSession();
String sql = "select count(*) from assets a join assettypes at on (at.id = a.assettype_id) ";
sql += "where a.currentlocation_id = " + paLocation.getId() + " and at.clamp = 1 and at.active = 1;";
list = session.createQuery(sql).list();
// for some reason, list is empty yet MySQL reports 40 records
// and the following two lines are never reached!
ret = list.size();
removeme = "WHAT???";
} catch (Exception ex) {
ret = -1; // explicitly set return
} finally {
return ret;
}
}
Towards the middle of the method you will see list = session.createQuery(sql).list();
For some reason, this is returning an empty list even though when the SQL is run manually, I get 40 results.
But the odd part is that once the .list() is called, it jumps to the finally block and never reaches the rest! So for testing, 'removeme' should equal WHAT??? but the debugger reports it as still ABC.
What gives?
You are using the wrong method. 'createQuery' is expecting HQL syntax. Change your method to 'createSQLQuery'

Categories