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.
Related
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.
I want to get all the data from the database using a where condition. But resultSet returning null values. But when I use an Integer instead of string it works fine, but that I don't want.
I'm not many experts in SQL but when I run a query in SQL server it works fine.
public JSONObject searchInternship1(String Category) throws SQLException {
ResultSet result;
Connection con = null;
PreparedStatement stmt = null;
JSONArray jsonArray = new JSONArray();
JSONObject mainObject1 = new JSONObject();
JSONObject jsonObject = new JSONObject();
try {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#144.217.163.57:1521:XE", "mad310team2", "anypw");
String sql;
sql = ("SELECT * FROM INTERNSHIP WHERE CATEGORY= ?");
stmt = con.prepareStatement(sql);
// con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
stmt.setString(1, Category);
result = stmt.executeQuery();
System.out.println("resultttt " + result);
String status;
Instant instant = Instant.now();
long time = instant.getEpochSecond();
if (result.next() == false) {
status = "Failed";
mainObject1.accumulate("Status :", status);
mainObject1.accumulate("Timestamp :", time);
mainObject1.accumulate("Message :", " Fetching Failed");
mainObject1.accumulate("why not", Category);
// System.out.println("hellooooo "+ result);
} else {
do {
mainObject1.accumulate("why not111", Category);
status = "Success";
jsonObject.accumulate("Id :", result.getInt("INT_ID"));
jsonObject.accumulate("CONTACT PERSON", result.getString("CONTACT_PERSON"));
jsonObject.accumulate("INCENTIVE", result.getString("INCENTIVE"));
jsonObject.accumulate(" VENUE", result.getString("VENUE"));
jsonObject.accumulate("DATE OF TEST", result.getDate("DATE_OF_TEST").toString());
jsonObject.accumulate("DATE OF TEST", result.getString("TIME_OF_TEST"));
jsonObject.accumulate("PROCEDURE", result.getString("PROCEDUREE"));
jsonObject.accumulate("No. OF VACANCIES", result.getInt("NO_OF_VACANCIES"));
jsonObject.accumulate("COMPANY ID", result.getInt("COMPANY_ID"));
jsonObject.accumulate("CATEGORY", result.getString("CATEGORY"));
jsonArray.add(jsonObject);
jsonObject.clear();
} while (result.next());
// result = result + r.getString("data");
mainObject1.accumulate("Details of jobs: ", jsonArray);
}
stmt.close();
con.close();
} catch (SQLException ex) {
// System.out.println("Error at111:" + ex.getClass().getName() + ex.getMessage());
Logger.getLogger(Register_Detail.class.getName()).log(Level.SEVERE, null, ex);
}
return mainObject1;
}
#GET
#Path("searchInternship&{value1}")
#Produces(MediaType.TEXT_PLAIN)
public String searchInternship(#PathParam("value1") String Category)
throws SQLException {
JSONObject result = searchInternship1(Category);
return result.toString();
}
I don't believe this is a JDBC issue. I believe this is an issue with how you are reading the data out of the result set.
At the top of your createInternship1 method you create a JSONObject object. Let's suppose at least one row comes back from the result set. For the first row read from the result set, your code then reads the values out of the result set and writes them into your JSONObject, before adding your JSONObject to your JSON array jsonArray.
So far, your code is doing what you want it to. You have a JSON array with a single object in it, containing the data read from the first row in the result set. However, the problem comes with your next step.
You then clear your JSONObject.
Your array doesn't contain a copy of your JSONObject, it contains the same object.
So at this point, your array now contains a single empty JSONObject. The data you read out of the result set has been deleted.
As your code proceeds through further rows in the result set, it encounters another problem. It reads more data into the same JSONObject created earlier, adds this same JSONObject (which is already in the array) to the array and then clears this same JSONObject again. You therefore end up with a JSON array containing the same empty JSONObject once for each row read from the result set.
I figured you're using the json-simple library for handling JSON. Initially I thought you were using org.json, but the JSONObject class in that library doesn't have a clear() method, whereas json-simple's JSONObject class does have this method. json-simple's JSONObject class extends java.util.HashMap, and calling the get() method of a HashMap returns null for a key that is not in the map. Your one JSONObject is empty, so no keys are in the map, and so null will always be returned from any call to the get() method of this object. This hopefully explains why you are getting null values returned.
You can fix this by creating a new JSONObject for each iteration of your do ... while loop instead of once at the top, adding that to your JSON array, and removing the line that clears the JSON object:
do {
JSONObject jsonObject = new JSONObject(); // add this line
mainObject1.accumulate("why not111", Category);
status = "Success";
jsonObject.accumulate("Id :", result.getInt("INT_ID"));
jsonObject.accumulate("CONTACT PERSON", result.getString("CONTACT_PERSON"));
// ... various similar lines omitted for clarity
jsonObject.accumulate("CATEGORY", result.getString("CATEGORY"));
jsonArray.add(jsonObject);
} while (result.next());
You'll also need to delete the line JSONObject jsonObject = new JSONObject(); further up in your code.
It is a question that has been asked many times but i didn't find any solution from the answers that they gave.
Basically im using the GSON to create instances of classes to JSON in order to serialize them and store it into the cloud save.
Here is the code
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
User user = dbmanager.getUser();
String user_json = gson.toJson(user);
saved_data.put("user", user_json);
The dbmanager.getUser(); is an Sql query that collects the user from the android database and return it as an instance of the User class.
Then i'm using the load method to load the data
public void converLoadData(String data) throws ParseException
{
if (data == null || data.trim().equals("")) return;
try {
User user = new User();
data = data.replace("\\\\", "\\");
JSONObject obj = new JSONObject(data);
System.out.println("data: " + obj.toString());
JSONObject user_object = obj.getJSONObject("user");
System.out.println("user " + user_object.toString());
String last_sync = obj.getString("last_sync");
java.util.Date db_sync = dbmanager.getLastSync(user.getID());
}
catch (JSONException ex) {
ex.printStackTrace();
Log.e(TAG, "Save data has a syntax error: " + data, ex);
}
catch (NumberFormatException ex) {
ex.printStackTrace();
throw new RuntimeException("Save data has an invalid number in it: " + data, ex);
}
}
The return of the println of data is this one
data: {"current":"{\"title\":\"Puzzle
2\",\"fnMoves\":[],\"solution_path\":\"puzzles\/2\/CKqbKz5f\/7b1886a261b0400768e75dea91948576.json\",\"puzzlecolors\":[0,0,0],\"puzzle_path\":\"puzzles\/2\/CKqbKz5f\/41a0b30fdfdf6685dd50c6019391cc00.tmx\",\"level_id\":2,\"locked\":false,\"level\":2,\"puzzle_site_id\":2,\"id\":2,\"score\":20,\"fnkeys\":1,\"solved\":false,\"difficulty\":1.0}","solved":"[{\"id\":1,\"puzzle_id\":1,\"puzzle_tries\":10,\"user_id\":1}]","user":"{\"personphoto\":\"https:\/\/lh4.googleusercontent.com\/-5XfDNwK1PwI\/AAAAAAAAAAI\/AAAAAAAAPs8\/C0onA9lyKvY\/photo.jpg?sz=50\",\"google_id\":\"fdgsdfgfgfgsdgsdf\",\"personname\":\"Test
Test\",\"last_sync\":\"2014-08-18
22:12:12\",\"lifes\":3,\"highscore\":13,\"ID\":1}","last_sync":"2014-08-18
22:12:12"}
and here is the error. This error has to do with the data value because i have back slash? i'm passing the data (which is string) into a JSON object and then i'm trying to collect the user element. using this JSONObject user_object = obj.getJSONObject("user"); and this is where i\m having the error. Anyone who can help me please? thank you
org.json.JSONException: Value {"personphoto":"https://lh4.googleusercontent.com/-5XfDNwK1PwI/AAAAAAAAAAI/AAAAAAAAPs8/C0onA9lyKvY/photo.jpg?sz=50","google_id":"104757400111626678244","personname":"George Panayi","last_sync":"2014-08-18 22:12:12","lifes":3,"highscore":13,"ID":1} at user of type java.lang.String cannot be converted to JSONObject
Solution: I'm using "remove" method to remove extra backslashes and quotes which cause bad format of the JSON Object
data = data.replace("\\", "");
data = data.replace("\"{", "{");
data = data.replace("}\"", "}");
data = data.replace("\"[", "[");
data = data.replace("]\"", "]");
I was able to get it working by cleaning up the JSON object a bit. I think it's just a bad formatting error.
First, the escape slashes, they need to be uniform or removed. I removed the ones escaping the double quotes, but left them in everywhere else.
Then I removed the double quotes around the nested objects and arrays. "{...}" to {...} and "[...]" to [...]
Seems to be all that was necessary.
{"current":{"puzzle_path":"puzzles\/2\/CKqbKz5f\/41a0b30fdfdf6685dd50c6019391cc00.tmx","solved":false,"score":20,"difficulty":1,"level_id":2,"id":2,"fnkeys":1,"title":"Puzzle\n2","level":2,"solution_path":"puzzles\/2\/CKqbKz5f\/7b1886a261b0400768e75dea91948576.json","puzzlecolors":[0,0,0],"puzzle_site_id":2,"locked":false,"fnMoves":[]},"user":{"ID":1,"lifes":3,"google_id":"fdgsdfgfgfgsdgsdf","highscore":13,"last_sync":"2014-08-18\n22:12:12","personname":"Test\nTest","personphoto":"https:\/\/lh4.googleusercontent.com\/-5XfDNwK1PwI\/AAAAAAAAAAI\/AAAAAAAAPs8\/C0onA9lyKvY\/photo.jpg?sz=50"},"solved":[{"puzzle_id":1,"id":1,"user_id":1,"puzzle_tries":10}],"last_sync":"2014-08-18\n22:12:12"}
I have a pretty introductory question that I hope can get answered rather easily.
Currently I am trying to write something that queries my DB, returns result set (list of account id's) and then sets those account id's into an array so that I can populate an object with the values.
My object is going to be used as input into another method I have written but I can't figure out how I go about populating my account_id field on it with the values in my array that I returned in the result set. There doesn't seem to be any "setter" methods for lack of a better term on my array of type String.
I was able to get the array to populate with acct_id's from the result set and print them out so I know that I do have information coming back.
Below is the snippet I currently have, any help/improvements I could make would be greatly appreciated!
try {
connection = DriverManager.getConnection(url, user, password);
st = connection.createStatement();
rs = st.executeQuery(sql);
List<Long> array = new ArrayList<Long>();
while (rs.next()) {
array.add((long) rs.getLong("acct_id"));
for (Integer i = 0; i < array.size(); i++) {
System.out.println(array.get(i));
GetSummaryRequest request = new GetSummaryRequest();
request.accountKey = new AccountDTO(array[i]);
}
}
} catch (SQLException e) {
System.out.println("Connection failed.");
e.printStackTrace();
return;
}
if (rs.next()) {
System.out.println(rs.getString(1));
} else
System.out.print("Failed. Try again");
}
If my understanding is correct you may need the code below which is used to store all the account id's inside an array and you can use this to pass as a parameter to another method.
ArrayList<GetSummaryRequest> array1=new ArrayList<GetSummaryRequest>();
GetSummaryRequest request = new GetSummaryRequest();
while (rs.next())
{
request=new GetSummaryRequest();
request.accountKey=rs.getString("acct_id");
array1.add(request);
}
Now you have ArrayList of GetSummaryRequest with accountKey for each object.
if i understand correctly accountkey is integer right?
you can use Integer.parseint('your string!') class to convert the string to int.
i hope it helps
First of all , storing newline separated values in one column is not a good practice. This is against atomicity principle and will lead you to problems soon - ex., total number of accounts? how do you find it?
Once you convince yourself with this, you can use only one loop like this
List<GetSummaryRequest> summaryRequests = new ArrayList<GetSummaryRequest>();
while (rs.next()) {
String em = rs.getString("acct_id");
GetSummaryRequest request = new GetSummaryRequest();
request.accountKey = em;
summaryRequests.add(request);
}
return summaryRequests;
Probably you need something like that:
// First you get all ids
List<String> accountsIds = new ArrayList<String>();
while (rs.next()) {
accountsIds.add(rs.getString("acct_id"));
}
// Then iterate ids
for (String id : accountsIds) {
GetSummaryRequest request = new GetSummaryRequest();
request.accountKey = id;
}
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") );
}