public String deleteCounterParty(List<CounterParty>counterParties)
{
String message = "";
for(CounterParty counterParty:counterParties) {
if (counterParty.getId() != null && counterPartyRepository.getById(counterParty.getId()) != null) {
counterPartyRepository.deleteById(counterParty.getId());
message="deleted successfully";
}
else {
message="id not found";
}
}
return message;
}
I'm using this method to delete rows by giving list of ids if the given id is found it is deleted,if not it throws this EmptyResultDataAccessException help me fix this
Data access exception thrown when a result was expected to have at least one row (or element) but zero rows (or elements) were actually returned.
Use a try-catch block to catch the exception if thrown and alter your logic accordingly so that when the code follows a happy path, at least one row is returned.
try { //code to delete rows } catch(final
EmptyResultDataAccessException e) { //exception message }
Related
I try to get patient information, by sending an ID to the server. I expect the result to be a JSONObject, as only one patient corresponds with the ID. However, what i get is a JSONArray. I have tried to do getJSONObject(0), but it gives this error:
Index 0 out of range [0..0)
Why i is an Array and not an Object, and how do i deal with it?
This is my java code in the activity:
new HttpRequestTask(
"getPatientFull",
new String[]{"ID"},
new String[]{PatientID}, new HttpRequestTask.ResultReceiver() {
#Override
public void processResult(String apiFunctionName, JSONObject result) {
if (result != null) {
try {
if (result.has("error")) {
shorttoast("ERROR: " + result.getString("error") + "saving patient file");
} else {
if (result.has("patient_details")) {
patientName = result.getJSONArray("patient_details").getJSONObject(0).getString("NAME");
shorttoast(patientName);
}
}
} catch (JSONException ex) {
shorttoast("ERROR" + ex.getLocalizedMessage());
}
} else
shorttoast("Retreiving failed");
}
}).execute();
The PatientID is defined earlier in the code (it's an existing patient id).
and this is the php API function that was defined by my teacher:
app.post("/getPatientFull", function (req, res) {
pool.getConnection(function (err, connection) {
connection.query('SELECT * FROM PatientDossier WHERE PATIENT_ID=?',
[req.query.ID],
function (error, results, fields) {
if (error) {
res.status(403).json({"error": error.code});
} else {
res.status(200).json({patient_details:results});
}
});
connection.release();
});
});
The PHP function does not return a single object, it returns an array.
So, you should expect a JSONArray on the Android side.
As to why getJSONObject(0) is giving you an out-of-bounds error, I'm not sure.
Try using the debugger to look at the JSONArray, and see what's in it. It's possible that you searched for a patient id that's not in the database, and the PHP code returned an empty array. Your code should be checking that anyway.
It also looks like maybe "result" is a JSONObject containing the array, under the key "patient_details", in which case, you need to get the value of "patient_details" and index into that array. If you show us the JSON response, it would be easier to tell.
i'm trying to extract from mysql database, but my code keeps throwing nullpointerexception and think its because no array is beeing created, what am i doing wrong ?
here's the code: -- thanks !
public ArrayList<String> getRow(String quEry, String db){
String url = "jdbc:mysql://localhost:3306/"+db;
try {
conn = DriverManager.getConnection(url, "root", "");
} catch (SQLException e) {
}
try{
query = conn.prepareStatement(quEry);
}catch(Exception e){
}
try {
getRow_Method_Result = query.executeQuery();
} catch (SQLException e) {
}
try{
while(getRow_Method_Result.next()){
row_result.add(getRow_Method_Result.getString(1));
row_result.add(getRow_Method_Result.getString(2));
row_result.add(getRow_Method_Result.getString(3));
row_result.add(getRow_Method_Result.getString(4));
}
}catch(Exception e){
}
return row_result;
}
public static void main(String[] args) {
ConectorBaseDatos OBJ_testGetRowMethod = new ConectorBaseDatos();
ArrayList<String> rowListResult_ofMethos = OBJ_testGetRowMethod.getRow("SELECT * FROM `arbitros`", "fifa");
System.out.println(rowListResult_ofMethos.toString());
}
i have tried to create this as a String[][] array but since this is a little more complicated decided to create it first as an ArrayList then this result insert it into ArrayList<ArrayList<String>> but just STUCK HERE
I will write here, as this may get a little long for comment.
rowListResult_ofMethods being null implies that your call to OBJ_testGetRowMethod.getRow("SELECT * FROMarbitros", "fifa") returned null.
Looking at your public ArrayList<String> getRow(String quEry, String db) method, I do not see where row_result is first initialized.
So, you should find and make sure row_result is initialized somewhere. (Probably something like row_result = new ArrayList<String>() somewhere.)
In addition, you should NEVER (I would say never, may vary for others) do nothing after catching an exception!
Do not do this:
try{
while(getRow_Method_Result.next()){
row_result.add(getRow_Method_Result.getString(1));
row_result.add(getRow_Method_Result.getString(2));
row_result.add(getRow_Method_Result.getString(3));
row_result.add(getRow_Method_Result.getString(4));
}
} catch(Exception e){
//Do not leave this blank!!! you must handle exception here !
// At least do e.printStackTrace(); to see exception during development.
}
As long as connection and query to your database was successful, I'm guessing the above row_result.add(getRow_Method_Result.getString(1)); would have thrown a NullPointerException. But this exception was discarded and no action was taken, as you left that part blank.
Where are you declaring ArrayList<String> row_result?(statically may be)
If you are initializing as ArrayList<String> row_result=null and you don't have any result set return then it will throw you NPE. And if you have result set then NPE will be inside very first line of while. Make sure you are initializing it as ArrayList row_result=new ArrayList();
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 - "
}
I have a method what return a list, but when i run the code, appears Unreachable statement
this method come from a aidl file and generate a map with the return.
code bellow:
List<String> list = new ArrayList<String>();
Public List<String> setMethod(Map map) {
ContentValues cv = null;
Iterator i = map.keySet().iterator();
Iterator j = map.values().iterator();
if(map.isEmpty() || map == null) {
return null;
} else {
try {
while(i.hasNext()) {
String str = (String) i.next();
Long l = (Long) j.next();
list.add(str);
cv.put(Storage.STR, str);
if(Provider.insert(Storage.Table, cv) < 0) {
return null;
}
}
if(list.isEmpty() || list == null) {
return null;
} else {
return mPathList;
}
} catch (Exception e) {
return null;
}
return list;
}
Anybody can give me a light what i can make for dolve it?
You are returning from try block as well as catch, so the last return statement will never be reached.
Your code has multiple return paths. You are returning from first if statement if your condition is met, in else part you have try block. In try you are returning based on if as well as else, so if no exception occurs you are guaranteed to return from try block, in case of exception you have a catch statement and you are returning from there as well. So there is no possibility that your code will continue further. Hence the last return statement is unreachable.
Just follow through your code. The last return statement will never be run because every other branch before that leads to an other return statement.
I've got the following code snippet that I'm thinking of refactoring to a more abstract application exception handler but I want to make sure I've got it as tidy as possible first
Any suggestions on how to improve this code or make it more resuable
int id = -1;
final StringBuilder errorMessage = new StringBuilder("Bad Input Value: ");
try {
id = Integer.parseInt(edtId.getText().toString());
} catch (final NumberFormatException e) {
errorMessage.append("Failed to parse id " + e.getMessage());
}
if (id < 0) {
errorToast(errorMessage.toString());
} else {
//go ahead an retreive values from database knowing the id has been parsed
//correctly to a positive int.
}
Why pre-assign id to a magic number?
try {
int id=Integer.parseInt(edtId.getText().toString());
//go on as normal
} catch (NumberFormatException e) {
//handle error
}