I am trying to use a String read from a row in an SQL database, but when I do, I get the following NullPointerException :
Exception in thread "main" java.lang.NullPointerException
at ReadCol.data(ReadCol.java:37)
at ReadCol.main(ReadCol.java:50)
My code is shown below...
public String[] array;
ResultSet rs=st.executeQuery("select * from ATTENDANCE");
while(rs.next()){
File file = new File("E:\\eclipse\\workspace\\AutoAttendanceSystem\\res\\AttendanceData.csv");
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
array = line.split(",");
// This is line 37 :
if(rs.getString(1).equals(array[0]) && rs.getString(7).equals(array[6])){
JOptionPane.showMessageDialog(null, "Can't Update Because record already exist");
}
}
Here is the SQL table's structure :
CREATE TABLE "ATTENDANCE" (
"ATTENDANT_NAME" VARCHAR2(4000),
"ATTENDANT_AGE" NUMBER,
"ATTENDANT_CONTACT_NO" NUMBER,
"ATTENDANT_DEPARTMENT_NAME" VARCHAR2(4000),
"REGISTRATION_NUM" VARCHAR2(50),
"ABSENT_PRESENT" VARCHAR2(4000) DEFAULT 'Absent',
"ATTENDANCE_TIME_DATE" VARCHAR2(4000)
)
And here is an example of a row in that table :
Sun 2016.08.14 at 11:21:43 PM PDT, null, null, Thu 2016.08.18 at 01:58:34 AM PDT, null, Thu 2016.08.18 at 02:13:26 AM PDT, null
What is the problem ?
What is going on
It appears that the problem is when you call rs.getString(7).equals(...) or rs.getString(1).equals : this means that getString has returned null.
This can happen for 2 reasons :
The column that you ask (in that case column 1 or 7) doesn't exist
(doesn't seem to be the case here given your SQL table structure)
a NULL value must have been stored in the column, and getString returns null, which is why calling equals on null throws an exception.
Readings about this :
Information about ResultSet.getString's return value: ResultSet's documentation.
Why calling a method on a reference that points to null throws a NullPointerException
How to solve the problem
First off, to know which column is causing the problem, separate the conditions on 2 lines and see which one throws an exception :
if(rs.getString(1).equals(array[0]) &&
rs.getString(7).equals(array[6])){
If it is ok for your database to hold NULL values, then what you should do, is test for it before applying equals :
if( ( rs.getString(1) == null && array[0] == null
|| rs.getString(1) != null && rs.getString(1).equals(array[0]) )
&& ... // same for 7th column
Side notes
You should refer to columns using their names rather their index.
To make the code easier to understand, you could store the strings you want to compare in variables, and only later test the conditions on these variables.
End result
String databaseResult1, databaseResult2, fileResult1, fileResult2;
// Start looping
// ...
databaseResult1 = rs.getString("ATTENDANT_NAME");
fileResult1 = array[0];
databaseResult2 = rs.getString("ATTENDANCE_TIME_DATE");
fileResult2 = array[6];
if(
( databaseResult1 == null && fileResult1 == null
|| databaseResult1 != null && databaseResult1.equals(fileResult1) )
&&
( databaseResult2 == null && fileResult2 == null
|| databaseResult2 != null && databaseResult2.equals(fileResult2) )
...
Related
There are 7 rows of output for table, how can I modify this so row 6 displays either of the three providers.
I tried something like this :
template.getProvider2() != null || template.getProvider3() != null ||
template.getProvider1() != null ?
template.getProvider2().getBusinessUnit(): "" ||
template.getProvider3().getBusinessUnit(): "" ||
template.getProvider3().getBusinessUnit(): "",
which gives me an error of StringBuilder not accepting the OR operator,
I'd appreciate any help on this.
Thanks
Here is my code:
public GetEmailTemplatesResponse getEmailTemplates() throws Exception {
StringBuilder stringBuilder = new StringBuilder();
String tableRow = "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>";
Map<String, EmailTemplate> templates = templateRedisCacheReader.getTemplatesByCacheType(CacheType.EMAIL_TEMPLATE);
templates.values()
.forEach(template -> stringBuilder.append(String.format(tableRow,
template.getTemplateId(),
template.getProvider1() != null ? template.getProvider1().getId() : "",
template.getProvider2() != null ? template.getProvider2().getId() : "",
template.getProvider3() != null ? template.getProvider3().getId() : "",
template.getEnv(),
template.getProvider2() != null ? template.getProvider2().getBusinessUnit(): "", // <--
template.getPriority()))
);
I tried to check if all the providers are null and if one of them is not null , then display bussiness unit for that provider
There's a function commonly used in SQL that returns the first non-null parameter called "coalesce". You could write a Java equivalent of that.
Object coalesce(Object... objects) {
for (Object obj : objects) {
if(obj != null) return obj;
}
return null;
}
...
Provider firstNonNullTemplate=(Provider) coalesce(template.getProvider1(), template.getProvider2(), template.getProvider3());
Here is my code. I am trying to use JUnit to test the deleteUsers() method, but everytime I write my test, it deletes all the users that I have in the database. How can i delete a single user? Below is the code for the method and for the test.
#Override
public boolean deleteUsers(List<String> ids) throws Exception {
StringBuilder sql = new StringBuilder();
sql.append("delete from user where ");
for (String id : ids) {
sql.append(" id = ? or");
}
String strSql = sql.toString().substring(0, sql.length() - 2) + ";";
PreparedStatement preparedStatement = this.connection.prepareStatement(strSql);
for (int i = 0; i < ids.size(); i++) {
preparedStatement.setInt(1 + i, Integer.parseInt(ids.get(i)));
}
int lines = preparedStatement.executeUpdate();
preparedStatement.close();
return lines > 0;
}
You're missing a check for empty input. In your test you pass an empty list to deleteUsers which results in this SQL statement:
delete from user wher;
I'd expect that the DBMS would reject this as invalid SQL but perhaps there are some where this is interpreted as delete from user which simply deletes all users. (As #SteveBosman pointed out the wher is interpreted as table alias as it is - due to the missing last e - no reserved word anymoere)
Basically you have 2 options. Either deleting all users by passing an empty list is a valid use case - in which case you should handle it properly by producing proper SQL. Or this is not expected and you should adapt your code to throw an Exception if ids is empty.
#Override
public boolean deleteUsers(List<String> ids) throws Exception {
if (ids == null || ids.size() == 0) {
throw new IllegalArgumentException("List of IDs must not be empty");
}
...
}
You could of course return false in case of an empty input as well to indicate no users were deleted.
To pass values to the deleteUsers method in your test you need to add values to the used list:
userDAOImpl.addUser("admin3", "111222");
final List<String> idsToDelete = new ArrayList<>();
idsToDelete.add("111222");
userDAOImpl.deleteUsers(idsToDelete);
The problem is caused by how the SQL is built. When deleteUsers is passed an empty list then the generated SQL will be:
delete from user wher
which will result in all data being deleted (the table user is given the alias "wher"). I highly recommend checking at the start of the method if the collection is empty and either raising an exception or returning.
Add the following check
if (ids == null || ids.isEmpty()) {
throw new IllegalArgumentException("ids must not be empty");
}
StringBuilder sql = new StringBuilder();
sql.append("delete from user where");
String orClause = "";
for (String id : ids) {
sql.append(orClause);
sql.append(" id = ?");
orClause = " or";
}
Can anyone please help in providing a code snippet to read 1 million records from excel using java
We have XSSF apache poi,but it is not able to read 500 k records as it is trying to read entire file at once,
"GC over limit exceeded" error is being thrown
I searched over the internet but I am getting examples only to write data of 1 million records into excel using java
Sure you can read 1 million records from excel using java , but you need a very big computer memory. if you run your application via eclipse , a very big memory is required. In fact , I read 181234 records via eclipse by java , it needs More than 11G memory, so , if you want to read 1 million records, think about the memory you need ......
below is the test code.
public class Test {
public static void main(String[] args) throws Exception {
File file = new File("C:\\opt\\upload\\1.xlsx");
InputStream in = new FileInputStream(file);
XSSFWorkbook xssfWorkbook = getXSSFWorkbook(in);
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
XSSFRow row = xssfSheet.getRow(0);
long time = System.currentTimeMillis();
NetworkParas bean = new NetworkParas();
bean.setCellId(Double.valueOf(row.getCell(0) == null ? null : row.getCell(0).toString()).intValue());
bean.setLac(Double.valueOf(row.getCell(1) == null ? null : row.getCell(1).toString()).intValue());
bean.setLongitude(Double.valueOf(row.getCell(2) == null ? null : row.getCell(2).toString()));
bean.setLatitude(Double.valueOf(row.getCell(3) == null ? null : row.getCell(3).toString()));
bean.setAntAzimuth(Double.valueOf(row.getCell(4) == null ? null : row.getCell(4).toString()).intValue());
bean.setRat(row.getCell(5) == null ? null : row.getCell(5).toString());
bean.setCity(row.getCell(6) == null ? null : row.getCell(6).toString());
bean.setCell(row.getCell(7) == null ? null : row.getCell(7).toString());
bean.setCellName(row.getCell(8) == null ? null : row.getCell(8).toString());
bean.setLocation(row.getCell(9) == null ? null : row.getCell(9).toString());
bean.setCellType(row.getCell(10) == null ? null : row.getCell(10).toString());
bean.setSiteId(row.getCell(11) == null ? null : row.getCell(11).toString());
bean.setSiteType(row.getCell(12) == null ? null : row.getCell(12).toString());
bean.setConf(row.getCell(13) == null ? null : row.getCell(13).toString());
bean.setAntHeight(Double.valueOf(row.getCell(14) == null ? null : row.getCell(14).toString()));
bean.setMtilt(Double.valueOf(row.getCell(15) == null ? null : row.getCell(15).toString()));
bean.setEtilt(Double.valueOf(row.getCell(16) == null ? null : row.getCell(16).toString()));
bean.setNe(row.getCell(17) == null ? null : row.getCell(17).toString());
bean.setArfcnDl(Double.valueOf(row.getCell(18) == null ? null : row.getCell(18).toString()).intValue());
bean.setScramblingCode(Double.valueOf(row.getCell(19) == null ? null : row.getCell(19).toString()).intValue());
bean.setCpichPower(Double.valueOf(row.getCell(20) == null ? null : row.getCell(20).toString()));
bean.setEnbId(Double.valueOf(row.getCell(22) == null ? null : row.getCell(22).toString()).intValue());
bean.setEci(Integer.valueOf(row.getCell(23) == null ? null : row.getCell(23).getCTCell().getV()));
bean.setLaccellId(row.getCell(26) == null ? null : row.getCell(26).getCTCell().getV());
System.out.println(bean);
time = System.currentTimeMillis() - time;
System.out.println("Elapsed Time :" + time);
}
public static XSSFWorkbook getXSSFWorkbook(InputStream in) throws IOException {
long time = System.currentTimeMillis();
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
System.out.println("\n*** Elapsed Time: " + ((System.currentTimeMillis()-time)/1000) + "s ");
return xssfWorkbook;
}
I am using hibernate to get data from oracle.I have Criterion object to make filter for hibernate select like this
Criterion cr6=null;
if(reqrrn != null)
{
cr6=Restrictions.eq("rrn", reqrrn);//o
}
else{
cr6=Restrictions.like("rrn", "",MatchMode.ANYWHERE);
}
Criterion cr20=null;
if(cardPrefix != null && cardPrefix != "")
{
cr20=Restrictions.eq("prefix", cardPrefix);
}
else{
cr20=Restrictions.like("prefix", "",MatchMode.ANYWHERE);
}
criteria.add(Restrictions.and(cr6, cr20));
i have filters like this, but it is usseless when value is null, for example
cardPrefix value is null in database i want to get all values for cardPrefix ,which are filled and null too, how can i do this ?
i solved it. it will be for all parameters like
if(cardPrefix != null && cardPrefix != "")
{
cr20=Restrictions.eq("prefix", cardPrefix);
}
else{
cr20=Restrictions.like("prefix", "",MatchMode.ANYWHERE);
cr1=Restrictions.isNull("prefix");
cr20=Restrictions.or(cr20, cr1);
}
I have a JSONObject which I am parsing and sometimes some of the data is null.
In this case, ReportId = null..so, I tried to use a ternary operator to prevent the ClassCastException, however, it doesn't work.
The specific object throwing the error has "ReportId":null....can I not do this?
Line:
item.setReportId((jsonObj.get("ReportId") != null || jsonObj.get("ReportId") != "null") ? (Integer)jsonObj.get("ReportId") : 0);
I just had a look at the documentation for JSONObject, it appears to have a number of convenience methods. For example:
item.setReportId( (!jsonObj.isNull("ReportId")) ? jsonObj.getInt("ReportId") : 0);
Try with following condition,
If there is valid numeric reportid in json then set the report id otherwise set 0 as report id
try{
reportId = (jsonObj.get("ReportId") != null) ? Integer.parseInt((String)jsonObj.get("ReportId")) : 0;
}catch(Exception ex){
reportId = 0;
}
item.setReportId(reportId);