Validation for Excel sheet using core java - java

I have built core java code to read excel data and push into database. And it works fine. Now I want to add some validatation checks to the excel sheet. I am not able to do that. Consider I have some columns which are SettleDate,TradeDate, TradeID, IFStatus, IFVersion, IFDate, IFTime. I want to do below vlidation rules.
Settle should not be more thatn TradeDate.
TradID should be 14 letteres.
IFStatus, IFVersion, IFDate, IFTime should be blank
Below is my code........
try {
Class forName = Class.forName("com.sybase.jdbc2.jdbc.SybDriver");
Connection con = null;
con = DriverManager.getConnection("jdbc:sybase:Tds:tkbgssvt1:4105", "kauai_rwu", "rwu_kauai");
System.out.println("Database connected to Sybase..");
con.setAutoCommit(false);
PreparedStatement pstm = null;
FileInputStream input = new FileInputStream(
"C:\\Users\\suresnar\\Desktop\\Mizu_FGloss\\Kauai_IN_Table_test.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
Row row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (Row) sheet.getRow(i);
DataFormatter formatter = new DataFormatter();
String TradeAction = formatter.formatCellValue(row.getCell(0));
String TradeID = formatter.formatCellValue(row.getCell(1));
String Version = formatter.formatCellValue(row.getCell(2));
String TradeType = formatter.formatCellValue(row.getCell(3));
String Book = formatter.formatCellValue(row.getCell(4));
String Direction = row.getCell(5).getStringCellValue();
String SafekeepFlag = row.getCell(6).getStringCellValue();
String OurSettlePlace = formatter.formatCellValue(row.getCell(7));
String OurSettleDepot = row.getCell(8).getStringCellValue();
String TheirSettlePlace = row.getCell(9).getStringCellValue();
String TheirSettleDepot = row.getCell(10).getStringCellValue();
String BrokerCode = row.getCell(11).getStringCellValue();
String CustomerCode = formatter.formatCellValue(row.getCell(12));
String ProductCode = formatter.formatCellValue(row.getCell(13));
String TradeDate = formatter.formatCellValue(row.getCell(14));
String TradeTime = formatter.formatCellValue(row.getCell(15));
String CreditPerson = row.getCell(16).getStringCellValue();
String Quantity = formatter.formatCellValue(row.getCell(17));
String Factor = formatter.formatCellValue(row.getCell(18));
String ActualQuantity = formatter.formatCellValue(row.getCell(19));
String SettleDate = formatter.formatCellValue(row.getCell(20));
String Price = formatter.formatCellValue(row.getCell(21));
String TradeCcy = row.getCell(22).getStringCellValue();
String TradeValue = formatter.formatCellValue(row.getCell(23));
String AccDays = formatter.formatCellValue(row.getCell(24));
String TradeAICcy = formatter.formatCellValue(row.getCell(25));
String TradeAI = formatter.formatCellValue(row.getCell(26));
String SettleAmt = formatter.formatCellValue(row.getCell(27));
String RateCalc = formatter.formatCellValue(row.getCell(28));
String FxRate = formatter.formatCellValue(row.getCell(29));
String SettleCcy = formatter.formatCellValue(row.getCell(30));
String SettleAmtInFX = formatter.formatCellValue(row.getCell(31));
String Memo1 = row.getCell(32).getStringCellValue();
String Memo2 = row.getCell(33).getStringCellValue();
String Memo3 = row.getCell(34).getStringCellValue();
String Memo4 = row.getCell(35).getStringCellValue();
String Memo5 = row.getCell(36).getStringCellValue();
String Remark1 = row.getCell(37).getStringCellValue();
String Remark2 = row.getCell(38).getStringCellValue();
String SelfStBrCode = formatter.formatCellValue(row.getCell(39));
String SelfStBrSubCode = formatter.formatCellValue(row.getCell(40));
String CustStBrCode = formatter.formatCellValue(row.getCell(41));
String CustStClCode = formatter.formatCellValue(row.getCell(42));
String CustStSubCode = formatter.formatCellValue(row.getCell(43));
String DiscretionFlg = formatter.formatCellValue(row.getCell(44));
String InputTime = formatter.formatCellValue(row.getCell(45));
String UpdateTime = formatter.formatCellValue(row.getCell(46));
String IFStatus = formatter.formatCellValue(row.getCell(47));
String IFVersion = formatter.formatCellValue(row.getCell(48));
String IFDate = formatter.formatCellValue(row.getCell(49));
String IFTime = formatter.formatCellValue(row.getCell(50));
String AzIFStatus = formatter.formatCellValue(row.getCell(51));
String AzIFVersion = formatter.formatCellValue(row.getCell(52));
String AzIFTime = formatter.formatCellValue(row.getCell(53));
String AzCKTime = formatter.formatCellValue(row.getCell(54));
String sql = "INSERT INTO FB_KAUAI_IN (\"my query\")";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Imported rows " + i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
}
Can anyone help me please?
your help is much appriciated...
Thanks,
Suresh N

I guess there's a couple of different ways to do this:
if you really own the Excel file and you create it. You can create your own formula to "validate" the cells you want.
you can create different classes for each type you want to validate and each "cell" will have it's own class/validation
you can manually create validation and apply for each field you want to validate (directly in java, per "String" you get from the
excel file).
since you (really) should change the SQL query to Hibernate for example, after that you can use hibernate validators (before inserting into db).

Related

Java REST API upon building string after get request replace null values with string vale

I am currently working on a Java application where I have an AsyncTask function get data from an API, then have a line reader and string builder create a large string, which I then pass to the postExecute function where I convert that string into a JSON object. I have tried creating a function that takes the string before post execute and replaces all null with "N/A", I have also tried checking in the String builder function but neither seem to make any changes to the null value. Here is an example of what the code looks like. I believe the error occurs when The string is converted into the JSON Object. This is a school project and I am not allowed to use external libraries.
String Builder:
BufferedReader reader = new BufferedReader(new InputStreamReader(httpClient.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
if (line.contains(null) || line.contains(""))
line += "N/A";
else
continue;
builder.append(line + "\n");
}
replaceNull Function:
public String removeUnwantedVal(String message) {
if (message.contains("null")) {
String replacement = "N/A";
message.replaceAll(null, replacement);
}
return message;
}
Post Execute JSON Object:
protected void onPostExecute(String message) {
TextView tv = findViewById(R.id.display);
System.out.println(message);
try {
JSONObject jsonAddress = new JSONObject(message);
// DISPLAY INFORMATION
String requesterIP = jsonAddress.getString("requester-ip");
String execTime = jsonAddress.getString("execution-time");
ipInfo.setIPAndTime(requesterIP, execTime);
// GEOGRAPHY
JSONObject geo = jsonAddress.getJSONObject("geo");
String countryName = geo.getString("country-name");
String capital = geo.getString("capital");
String iso = geo.getString("country-iso-code");
String city = geo.getString("city");
double longitude = geo.getDouble("longitude");
double latitude = geo.getDouble("latitude");
location = new Location(countryName, capital, iso, city, longitude, latitude);
// CURRENCY
JSONObject currency = jsonAddress.getJSONObject("currency");
String currencyNativeName = currency.getString("native-name");
String currencyCode = currency.getString("code");
String currencyName = currency.getString("name");
String currencySymbol = currency.getString("symbol");
Currency = new Currency(currencyNativeName, currencyCode, currencyName, currencySymbol);
// ASN
JSONObject asn = jsonAddress.getJSONObject("asn");
String asnName = asn.getString("name");
String asnDomain = asn.getString("domain");
String asnOrganization = asn.getString("organization");
String asnCode = asn.getString("asn");
String asnType = asn.getString("type");
ASN = new ASN(asnName, asnDomain, asnOrganization, asnCode, asnType);
// TIMEZONE
JSONObject timezone = jsonAddress.getJSONObject("timezone");
String timezoneName = timezone.getString("microsoft-name");
String dateTime = timezone.getString("date-time");
String ianaName = timezone.getString("iana-name");
Timezone = new Timezone(timezoneName, dateTime, ianaName);
// SECURITY
JSONObject security = jsonAddress.getJSONObject("security");
boolean isCrawler = security.getBoolean("is-crawler");
boolean isProxy = security.getBoolean("is-proxy");
boolean isTor = security.getBoolean("is-tor");
Security = new Security(isCrawler, isProxy, isTor);
container = new IPContainer(ipInfo, Currency, location, Security, ASN, Timezone);
tv.setText(container.displayGeneral());
} catch (JSONException e) {
tv.setText(e.toString());
e.printStackTrace();
}
}
I have resolved the issue. When I was getting the code I thought that null values could not be displayed, this was incorrect. The problem was that I was trying to create an object out of null, sometimes the value came back as null instead of as an object. Sorry, beginner coder :)

SimpleDateFormat returning wrong time value ( 00:00:00) [duplicate]

This question already has answers here:
JDBC ResultSet getDate losing precision
(3 answers)
Closed 7 years ago.
I'm having an issue using the SimpleDateFormat component.
I have a date stored in my database as a DateTime, and i would like to get the value of this datetime in my application.
I'm using a SimpleDateFormat in order to do this, but the problem is that it always returns me 00:00:00 as Time. The date is well returned though.
So i'm doing as follows :
private final static SimpleDateFormat ft = new SimpleDateFormat("dd.MM - HH:mm:ss");
public Push(int idp, String titrefr, String contenufr, String titreuk, String contenuuk, String pays, String marche, String type, Date datep, int isImportant, String image) {
super();
this.idp = idp;
this.titrefr = titrefr;
this.contenufr= contenufr;
this.titreuk = titreuk;
this.contenuuk= contenuuk;
this.pays = pays;
this.marche = marche;
this.type = type;
this.datep = ft.format(datep);
this.isImportant = isImportant;
this.image = image;
System.out.println(this.datep);
}
Here is the method where I get the date :
Modele.java:
public List<Push> getPushfr() {
String queryPushfr = "SELECT idp,titrefr,contenufr,titreuk,contenuuk,pays,marche,type,datep,isImportant, image FROM push WHERE datep > DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY datep DESC;";
try {
connexion = ConnexionBDD.getConnexion();
PreparedStatement pstmt = connexion.prepareStatement(queryPushfr);
resultat = pstmt.executeQuery(queryPushfr);
while (resultat.next()) {
int idp = resultat.getInt("idp");
String titrefr = resultat.getString("titrefr");
String contenufr = resultat.getString("contenufr");
String titreuk = resultat.getString("titreuk");
String contenuuk = resultat.getString("contenuuk");
String pays = resultat.getString("pays");
String marche = resultat.getString("marche");
String type = resultat.getString("type");
Date datep = resultat.getDate("datep");
int isImportant = resultat.getInt("isImportant");
String image = resultat.getString("image");
this.pushfr.add(
new Push(idp, titrefr, contenufr, titreuk, contenuuk, pays, marche, type, datep, isImportant,image));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
return pushfr;
}
In my database the date is :
2015-09-03 16:13:09
The output i get from my System.out.println(datep) is
03.09 - 00:00:00
I've no idea why it's not returning me the time properly..
If you are using java.sql.Date you will lose information about the time.
java.sql.Date corresponds to SQL DATE which means it stores years,
months and days while hour, minute, second and millisecond are
ignored.
Change code to:
public List<Push> getPushfr() {
String queryPushfr = "SELECT idp,titrefr,contenufr,titreuk,contenuuk,pays,marche,type,datep,isImportant, image FROM push WHERE datep > DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY datep DESC;";
try {
connexion = ConnexionBDD.getConnexion();
PreparedStatement pstmt = connexion.prepareStatement(queryPushfr);
resultat = pstmt.executeQuery(queryPushfr);
while (resultat.next()) {
int idp = resultat.getInt("idp");
String titrefr = resultat.getString("titrefr");
String contenufr = resultat.getString("contenufr");
String titreuk = resultat.getString("titreuk");
String contenuuk = resultat.getString("contenuuk");
String pays = resultat.getString("pays");
String marche = resultat.getString("marche");
String type = resultat.getString("type");
Date datep = resultat.getTimestamp("datep");
int isImportant = resultat.getInt("isImportant");
String image = resultat.getString("image");
this.pushfr.add(
new Push(idp, titrefr, contenufr, titreuk, contenuuk, pays, marche, type, datep, isImportant,image));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
return pushfr;
}
PD:I recomend you to store the TimeStamt in milisecons in the database.
If you are loading results from a ResultSet, use getTimestamp method, not getDate. See JDBC ResultSet getDate losing precision

nonuniqueobjectexception when Updating Database and Database creating new records instead of updating existing ones

I'm having an issue which I don't really understand, especially since I just started working with databases. I keep getting an nonuniqueobjectexception, when I try to save two instances of the project into the database. When I save the session for Project it will keep all the information and update the database accordingly but the Inspection table which is connected to the Project database will continue to add new entries. I tried multiple fixes of trying to throw exceptions but I can't figure out a way to save the information in the table without creating new entries in the instance table. Can anyone give me any advice on how to tackle this issue and where to look?
public static void editProject(Long warehouseID, Long managerID, Long supervisorID,
Long classID, Long projectItemID, Long statusID,
Long stageID, Long typeID, String scope, Map<String, String>params, Long inspectionTN)
throws ClassNotFoundException, ParseException
{
//Initialize Services
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
//Get essential project data
Warehouse warehouse = (Warehouse) ProjectObjectService.get(warehouseID, "Warehouse");
Person manager = (Person) ProjectObjectService.get(new Long(managerID), "Person");
Person supervisor = (Person) ProjectObjectService.get(new Long(supervisorID), "Person");
ProjectClass projectClass = (ProjectClass) ProjectObjectService.get(new Long(classID), "ProjectClass");
ProjectStatus status = (ProjectStatus) ProjectObjectService.get(new Long(statusID), "ProjectStatus");
ProjectItem item = (ProjectItem) ProjectObjectService.get(new Long(projectItemID), "ProjectItem");
ProjectStage stage = (ProjectStage) ProjectObjectService.get(stageID, "ProjectStage");
ProjectType pType = (ProjectType) ProjectObjectService.get(typeID, "ProjectType");
String mcsNumString = params.get("mcsNumber");
//ID's
String iIDString = params.get("inspectionID");
String closeoutIDString = params.get("closeoutID");
int mcsNum = -1;
Long iID = (long)-1;
Long closeoutID = (long)-1;
//Parse mcsNumber, change to -1 if it's not a number
try
{
mcsNum = Integer.parseInt(mcsNumString);
iID = Long.parseLong(iIDString);
closeoutID = Long.parseLong(closeoutIDString);
}catch(Exception e){}
//Inspections inspections=(Inspections) ProjectObjectService.get(iID, "Inspections");
int shouldInvoice = Integer.parseInt(params.get("shouldInvoice"));
int actualInvoice = Integer.parseInt(params.get("actualInvoice"));
String notes = params.get("notes");
//Additional fields
String zachNotes = params.get("zachUpdates");
String cost = params.get("cost");
String customerNumber = params.get("customerNumber");
//Parse change orders from strong
String changeOrderJsonString = params.get("coItems");
ChangeOrderService orderService = new ChangeOrderService();
HashSet<ChangeOrder> changeOrders = ChangeOrderService.getChangeOrdersFromString(changeOrderJsonString);
Date fsalvageDate = null;
Date finitiatedDate = null;
Date fsurvey = null;
Date fcostco = null;
Date fproposal = null;
Date fasBuilts = null;
Date fpunchList = null;
Date falarmHvac = null;
Date fverisae = null;
Date fcloseoutBook = null;
Date fcloseoutNotes = null;
Date fstart = null;
Date fscheduled = null;
Date factual = null;
Date fairGas = null;
Date fpermits = null;
Date permitApp = null;
Date fframing = null ;
Date fceiling = null;
Date froughMech = null;
Date froughElec= null;
Date froughPlumb = null;
Date fmechLightSmoke = null;
Date fmechFinal = null;
Date felecFinal = null;
Date fplumbFinal = null;
Date ffireMarshal = null;
Date fhealth = null;
Date fbuildFinal = null;
//assign values to dates, if they are not null
if (!(params.get("salvageDate")).isEmpty())
fsalvageDate = formatter.parse(params.get("salvageDate"));
if (!(params.get("initiated")).isEmpty())
finitiatedDate = formatter.parse(params.get("initiated"));
if (!(params.get("survey")).isEmpty())
fsurvey = formatter.parse(params.get("survey"));
if (!(params.get("costco")).isEmpty())
fcostco = formatter.parse(params.get("costco"));
if (!(params.get("proposal")).isEmpty())
fproposal = formatter.parse(params.get("proposal"));
if (!(params.get("asBuilts")).isEmpty())
fasBuilts = formatter.parse(params.get("asBuilts"));
if (!(params.get("punchList")).isEmpty())
fpunchList = formatter.parse(params.get("punchList"));
if (!(params.get("alarmHvac")).isEmpty())
falarmHvac = formatter.parse(params.get("alarmHvac"));
if (!params.get("verisae").isEmpty())
fverisae = formatter.parse(params.get("verisae"));
if (!params.get("startDate").isEmpty())
fstart = formatter.parse(params.get("startDate"));
if (!params.get("scheduledTurnover").isEmpty())
fscheduled = formatter.parse(params.get("scheduledTurnover"));
if (!params.get("actualTurnover").isEmpty())
factual = formatter.parse(params.get("actualTurnover"));
if (!params.get("airGas").isEmpty())
fairGas = formatter.parse(params.get("airGas"));
if (!params.get("permits").isEmpty())
fpermits = formatter.parse(params.get("permits"));
if (!params.get("permitApp").isEmpty())
permitApp = formatter.parse(params.get("permitApp"));
if(!params.get("framing").isEmpty())
fframing = formatter.parse(params.get("framing"));
if(!params.get("ceiling").isEmpty())
fceiling = formatter.parse(params.get("ceiling"));
if(!params.get("roughMech").isEmpty())
froughMech = formatter.parse(params.get("roughMech"));
if(!params.get("roughElec").isEmpty())
froughElec = formatter.parse(params.get("roughElec"));
if(!params.get("roughPlumb").isEmpty())
froughPlumb = formatter.parse(params.get("roughPlumb"));
if(!params.get("mechLightSmoke").isEmpty())
fmechLightSmoke = formatter.parse(params.get("mechLightSmoke"));
if(!params.get("mechFinal").isEmpty())
fmechFinal = formatter.parse(params.get("mechFinal"));
if(!params.get("elecFinal").isEmpty())
felecFinal = formatter.parse(params.get("elecFinal"));
if(!params.get("plumbFinal").isEmpty())
fplumbFinal = formatter.parse(params.get("plumbFinal"));
if(!params.get("fireMarshal").isEmpty())
ffireMarshal = formatter.parse(params.get("fireMarshal"));
if(!params.get("health").isEmpty())
fhealth = formatter.parse(params.get("health"));
if(!params.get("buildFinal").isEmpty())
fbuildFinal = formatter.parse(params.get("buildFinal"));
CloseoutDetails cd = null;
if(cd==null)
{
cd = new CloseoutDetails();
System.out.println("CloseoutDetails was empty in edit");
}
//Closeout fields
cd.setPunchList(fpunchList);
cd.setAsBuilts(fasBuilts);
cd.setAirGas(fairGas);
cd.setAlarmHvacForm(falarmHvac);
cd.setCloseoutBook(fcloseoutBook);
cd.setCloseoutNotes(fcloseoutNotes);
cd.setPermitsClosed(fpermits);
cd.setPunchList(fpunchList);
cd.setVerisaeShutdownReport(fverisae);
//need to add salvage amount and date
Inspections inspections = null;
//create inspections Object.
if(inspections==null)
{
inspections = new Inspections();
System.out.println("Inpsections was empty in edit");
}
//set inspection fields
inspections.setTicketNumber(inspectionTN);
inspections.setFraming(fframing);
inspections.setCeiling(fceiling);
inspections.setRoughin_Mechanical(froughMech);
inspections.setRoughin_Electric(froughElec);
inspections.setRoughin_Plumbing(froughPlumb);
inspections.setMechanicalLightSmoke(fmechLightSmoke);
inspections.setMechanical_Final(fmechFinal);
inspections.setElectrical_Final(felecFinal);
inspections.setPlumbing_Final(fplumbFinal);
inspections.setFire_Marshal(ffireMarshal);
inspections.setHealth(fhealth);
inspections.setBuilding_Final(fbuildFinal);
/*try{
inspections.setId(iID);
ProjectObjectService.editObject("Inspections",iID,inspections);
}catch (NonUniqueObjectException nuoe){}*/
//Create new project to replace the old one
Project p = new Project();
p.setMcsNumber(mcsNum);
p.setProjectClass(projectClass);
p.addProjectManager(manager);
p.addSupervisor(supervisor);
p.setStatus(status);
p.setWarehouse(warehouse);
p.setScope(scope);
p.setProjectItem(item);
p.setStage(stage);
p.setProjectInitiatedDate(finitiatedDate);
p.setSiteSurvey(fsurvey);
p.setCostcoDueDate(fcostco);
p.setProposalSubmitted(fproposal);
p.setScheduledStartDate(fstart);
p.setScheduledTurnover(fscheduled);
p.setActualTurnover(factual);
p.setShouldInvoice(shouldInvoice);
p.setInvoiced(actualInvoice);
p.setProjectNotes(notes);
p.setChangeOrders(changeOrders);
p.setProjectType(pType);
p.setZachUpdates(zachNotes);
p.setCost(cost);
p.setCustomerNumber(customerNumber);
p.setPermitApplication(permitApp);
p.setCloseoutDetails(cd);
p.setInspections(inspections);
//Replace the old project with the new project.
Long id = Long.parseLong(params.get("projectID"));
//ProjectObjectService.editObject("Project", id,p);
long[] iDs = {iID,/*closeoutID,*/id} ;
String[] domains = {"Inspections",/*"CloseoutDetails",*/"Project" };
ProjectObject[] objects ={inspections, /*cd,*/ p};
inspections.setId(iID);
ProjectObjectService.editObject("Project",id,p);
}
public static Object get(Long id, String domain) throws ClassNotFoundException
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
//Get the Class from parsing the "domain" string.
Class c = Class.forName("projectObjects."+domain);
//Get object from database that matches the id
Object o = session.get(c, id);
tx.commit();
return o;
}

Saving the values of a string to another class and retrieving it

I am currently trying to save the values of a string to another class file in JAVA called Memory.JAVA. The reason why I am doing this is because variables are not saved outside the Try - Catch Blocks. Therefore I initiate the class in the try catch block by using this code:
Memory mem = new Memory();
And then when I want to save a string, I use the following:
mem.brother1ID = "Whatever";
The reason why I am not creating it as a new String is because in the Memory class, I have already initiated this string. To test that this has been saved, I have used System.out.println to print out the result which in this case was "Whatever" but when I try to get the same result printed out in the same class, I get the result "null". Does anyone have any suggestions regarding my issue? Please feel free to comment below. Thanks!
UPDATE:
Some code posted below:
private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {
try {
Memory mem = new Memory();
String sql = "select * from userInfo where firstName= ? OR lastname = ?";
pst=conn.prepareStatement(sql);
pst.setString(1, searchField.getText());
pst.setString(2, searchField.getText());
rs=pst.executeQuery();
if(rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String placeOfResidence = rs.getString("placeOfResidence");
String employmentStatus = rs.getString("employmentStatus");
String currentEmployer = rs.getString("currentEmployer");
String taxStatus = rs.getString("taxStatus");
String dateOfBirth = rs.getString("dateOfBirth");
String mother = rs.getString("mother");
String father = rs.getString("father");
String brother1 = rs.getString("brother1");
String brother2 = rs.getString("brother2");
String brother3 = rs.getString("brother3");
String brother4 = rs.getString("brother4");
String brother5 = rs.getString("brother5");
String sister1 = rs.getString("sister1");
String sister2 = rs.getString("sister2");
String sister3 = rs.getString("sister3");
String sister4 = rs.getString("sister4");
String sister5 = rs.getString("sister5");
mem.brother1ID = rs.getString("brother1ID");
mem.brother2ID = rs.getString("brother2ID");
mem.brother3ID = rs.getString("brother3ID");
mem.brother4ID = rs.getString("brother4ID");
mem.brother5ID = rs.getString("brother5ID");
mem.sister1ID = rs.getString("sister1ID");
mem.sister2ID = rs.getString("sister2ID");
mem.sister3ID = rs.getString("sister3ID");
mem.sister4ID = rs.getString("sister4ID");
mem.sister5ID = rs.getString("sister5ID");
mem.fatherID = rs.getString("fatherID");
mem.motherID = rs.getString("motherID");
System.out.println(mem.brother1ID);
System.out.println(firstName + " " + lastName);
firstNameField.setText(firstName);
lastNameField.setText(lastName);
placeOfResidenceField.setText(placeOfResidence);
employmentStatusField.setText(employmentStatus);
currentEmployerField.setText(currentEmployer);
taxStatusField.setText(taxStatus);
dateOfBirthField.setText(dateOfBirth);
motherField.setText(mother);
fatherField.setText(father);
brothersField1.setText(brother1);
brothersField2.setText(brother2);
brothersField3.setText(brother3);
brothersField4.setText(brother4);
brothersField5.setText(brother5);
sisterField1.setText(sister1);
sisterField2.setText(sister2);
sisterField3.setText(sister3);
sisterField4.setText(sister4);
sisterField5.setText(sister5);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
And this is when I try to get the same results of System.out.println as before:
private void brotherViewButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Memory mem = new Memory();
String sql = "select * from userInfo where id=?";
pst=conn.prepareStatement(sql);
String IDNO = mem.brother1ID;
System.out.println(IDNO);
pst.setString(1, IDNO);
rs=pst.executeQuery();
if(rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String placeOfResidence = rs.getString("placeOfResidence");
String employmentStatus = rs.getString("employmentStatus");
String currentEmployer = rs.getString("currentEmployer");
String taxStatus = rs.getString("taxStatus");
String dateOfBirth = rs.getString("dateOfBirth");
String mother = rs.getString("mother");
String father = rs.getString("father");
String brother1 = rs.getString("brother1");
String brother2 = rs.getString("brother2");
String brother3 = rs.getString("brother3");
String brother4 = rs.getString("brother4");
String brother5 = rs.getString("brother5");
String sister1 = rs.getString("sister1");
String sister2 = rs.getString("sister2");
String sister3 = rs.getString("sister3");
String sister4 = rs.getString("sister4");
String sister5 = rs.getString("sister5");
System.out.println(firstName + " " + lastName);
firstNameField.setText(firstName);
lastNameField.setText(lastName);
placeOfResidenceField.setText(placeOfResidence);
employmentStatusField.setText(employmentStatus);
currentEmployerField.setText(currentEmployer);
taxStatusField.setText(taxStatus);
dateOfBirthField.setText(dateOfBirth);
motherField.setText(mother);
fatherField.setText(father);
brothersField1.setText(brother1);
brothersField2.setText(brother2);
brothersField3.setText(brother3);
brothersField4.setText(brother4);
brothersField5.setText(brother5);
sisterField1.setText(sister1);
sisterField2.setText(sister2);
sisterField3.setText(sister3);
sisterField4.setText(sister4);
sisterField5.setText(sister5);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
The reason the value brother1ID in your Memory object is null is because you're using a new instance of that object.
I strongly recommend you read up on how object instances are scoped in Java, and what it means to create a new instance, versus using an existing one.
For example, when you do this:
Memory mem = new Memory();
mem.brother1ID = "1234";
mem = new Memory();
System.out.println(mem.brother1ID);
The value printed will be null. This is because you're using a new instance of that class. If you wanted to maintain the values throughout multiple method calls, your best bet might be to save the Memory object as an instance variable of whatever class contains the methods you've shown. i.e.:
private Memory memory = new Memory();
...
private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {
// Use 'this.memory'
this.memory.brother1ID = "1234";
//(or)
System.out.println(this.memory.brother1ID);
}
private void brotherViewButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Use 'this.memory'
}
Please look at here
try {
Memory mem = new Memory();
String sql = "select * from userInfo where id=?";
pst=conn.prepareStatement(sql);
String IDNO = mem.brother1ID;
System.out.println(IDNO);
You are creating the object of Memory and not setting any value.
then you are trying to print the brotherId which will be null, all String variables will be initialised to null, that is why you are getting 'null'. what you can do is put the printing statement out of the try catch block at he bottom , if there are any records in your database, it will print out the last records brotherId.

I am not able to read the records with null date field in MySQL using java?

here is the code
private ResultSet rsResult;
try
{
rsResult = DBProcess.statement.executeQuery("SELECT * FROM patients");
}//end try
catch (SQLException ex)
{
out.println("<I>exception</I><br>");
Logger.getLogger(cUserLogin.class.getName()).log(Level.SEVERE, null, ex);
}//end catch
while (rsResult.next())
{
BigDecimal bdPatientID = rsResult.getBigDecimal("patient_id");
String strFirstname = rsResult.getString("first_name");
String strLastname = rsResult.getString("last_name");
String strMiddlename = rsResult.getString("middle_name");
String strGeneder = rsResult.getString("gender");
String strMeritalStatus = rsResult.getString("marital_status");
BigDecimal bdPhoneNo = rsResult.getBigDecimal("phone_no");
String strAddress = rsResult.getString("address");
String strDOB = rsResult.getDate("birth_dt").toString();
String strDOE = rsResult.getDate("dt_of_exam").toString();
}
i am not able to read records that are present after a recode which holds the null DATE field what can i do to get raid of this....
If rsResult.getDate("birth_dt") returns null, than calling toString() would cause a NullPointerException
You could rewrite this as:
String strDOB = rsResult.getDate("birth_dt") == null ? "" : rsResult.getDate("birth_dt").toString();

Categories

Resources