I written following code but it throws a "Resultset exhausted" error.
String dt = rs.getTimestamp("GuaranteeDate")+"";
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat1.parse(dt);
DateTime dateTime = new DateTime(date);
Integer attributeID = 0;
String query1 ="select distinct M_attributesetinstance_id from M_storage where m_Product_id="+M_Product_ID;
attributeID = DB.getSQLValue(trxName, query1);
Timestamp MaufacuringDate = null;
String query = "select manufacturingdate from m_attributesetinstance where m_attributesetinstance_id="+attributeID;
try
{
pstmt = null;
rs = null;
pstmt = DB.prepareStatement(query.toString(),null);
rs = pstmt.executeQuery();
while (rs.next())
{
MaufacuringDate = rs.getTimestamp("manufacturingdate");
}
}
catch (Exception e)
{
e.printStackTrace();
}
if (MaufacuringDate!= null)
{
DateTime ManufacturingDate = new DateTime(MaufacuringDate);
try
{
if((!"".equalsIgnoreCase(dt) || dt!=null) && percentage>=0 && GuaranteeDate != null)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Date d1 = c1.getTime();
DateTime dateTime1 = new DateTime(d1);
try
{
// c1.setTime(sdf.parse(dt));
// ReadableInstant date2;
Days d = Days.daysBetween(ManufacturingDate, dateTime);
int days = d.getDays();
float calulateddays = (float)(days*(percentage/100.0f));
Integer roundeddays = Math.round(calulateddays);
c1.setTime(sdf.parse(dt));
c1.add(Calendar.DATE, -roundeddays); // number of days to add
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = dateFormat.parse(sdf.format(c1.getTime()));
MinGuaranteeDate = new java.sql.Timestamp(parsedDate.getTime());
}
catch (Exception e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
}
catch (ParseException e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
}
else
{
continue;
}
}
catch(Exception e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
System.out.println("MinGuaranteeDate :"+MinGuaranteeDate);
System.out.println("TodayDate :"+GuaranteeDate);
if(MinGuaranteeDate==null || MinGuaranteeDate.after(GuaranteeDate))
{
continue;
}
}
else
{
Timestamp GRNDate = null;
String query2 = "select distinct Movementdate from M_inout m "
+"inner join m_inoutline mil ON (m.M_Inout_ID = mil.M_Inout_id) where mil.M_Product_Id="+M_Product_ID;
try
{
pstmt = null;
rs = null;
pstmt = DB.prepareStatement(query2.toString(),null);
rs = pstmt.executeQuery();
while (rs.next())
{
GRNDate = rs.getTimestamp("Movementdate");
}
}
catch (Exception e)
{
e.printStackTrace();
}
// String dt1 = rs.getTimestamp("GuaranteeDate")+"";
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = dateFormat1.parse(dt);
DateTime dateTime2 = new DateTime(date1);
DateTime GRDate = new DateTime(GRNDate);
try{
if((!"".equalsIgnoreCase(dt) || dt!=null) && percentage>=0 && GuaranteeDate!=null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Date d1 = c1.getTime();
//DateTime dateTime1 = new DateTime(d1);
try {
// c1.setTime(sdf.parse(dt));
//ReadableInstant date2;
Days d = Days.daysBetween(GRDate, dateTime);
int days = d.getDays();
float calulateddays = (float)(days*(percentage/100.0f));
Integer roundeddays = Math.round(calulateddays);
c1.setTime(sdf.parse(dt));
c1.add(Calendar.DATE, -roundeddays); // number of days to add
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = dateFormat.parse(sdf.format(c1.getTime()));
MinGuaranteeDate = new java.sql.Timestamp(parsedDate.getTime());
}catch(Exception e){
MinGuaranteeDate = null;
e.printStackTrace();
}
} catch (ParseException e) {
MinGuaranteeDate = null;
e.printStackTrace();
}
}
else {
continue;
}
}catch(Exception e) {
MinGuaranteeDate = null;
e.printStackTrace();
}
System.out.println("MinGuaranteeDate :"+MinGuaranteeDate);
System.out.println("TodayDate :"+GuaranteeDate);
if(MinGuaranteeDate==null || MinGuaranteeDate.before(GuaranteeDate)) {
continue;
}
}
}
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
}
}
} catch (Exception e) {
s_log.log(Level.SEVERE, sql, e);
} finally {
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
in above code gives the error on statement of bigdecimal
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
on this line
Kindly help me out
You need to find out whether MStorage calls rs.next() again, as you already used up all the results within another block:
while (rs.next())
{
MaufacuringDate = rs.getTimestamp("manufacturingdate");
}
I guess you have iterated over the record using Resultset object rs and now your rs cursor is at the end of the record/ or we can say it not pointing to any record.
Still your code below is using rs object which is exhausted and not pointing to any record/table row.
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
Possible solution :: Create a new statement, execute query and get the new ResultSet object whose cursor will be at the start of record (Note: Cursor at -1 (use .next())) and iterate over the record ad get the required result.
OR use some logic inside previous iteration over record and get the result there itself instead of iterating again .
Related
I am developing a system that manages stock for a project and am trying to get a list of stock items that are close to their expiration date
This is what the table is created as:
Query_Statement.executeUpdate("CREATE TABLE STOCK_PURCHASE ( SP_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "USER_ID INTEGER,STOCK_ID INTEGER,SUPPLIER_ID INTEGER,SP_ENTRY_DATE TEXT,"
+ "SP_PURCHASE_PRICE REAL, SP_SELLBY_DATE TEXT, SP_QUANTITY REAL,"
+ "FOREIGN KEY (USER_ID) REFERENCES USER (USER_ID),"
+ "FOREIGN KEY (STOCK_ID) REFERENCES STOCK (STOCK_ID),"
+ "FOREIGN KEY (SUPPLIER_ID) REFERENCES SUPPLIER (SUPPLIER_ID))");
This is the function to get that I use:
public ArrayList<String> GetExpiredStock(){
Connection dbConnection = null;
ResultSet list = null;
ArrayList<String> ls = new ArrayList<String>();
LocalDate currentDate = LocalDate.now();
//System.out.println(today);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try {
dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");
Statement Query_Statement = dbConnection.createStatement();
Query_Statement.setQueryTimeout(10);
list = Query_Statement.executeQuery("SELECT SP_ENTRY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works
while (list.next()) {
try {
LocalDate expDate = LocalDate.parse(list.getString("SP_SELLBY_DATE"), formatter);
LocalDate monthAway = expDate.minusMonths(1);
System.out.println(currentDate);
if(currentDate.isAfter(monthAway)) {
int id = list.getInt("STOCK_ID");
ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);
ls.add(ids.getString("STOCK_NAME") + "\t\t" +
list.getString("SP_SELLBY_DATE") + getStockQuant(list.getInt("STOCK_ID"),
currentDate));
}
}catch(SQLException e) {
System.err.println(e);
continue;
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
try {
if (dbConnection != null)
dbConnection.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return ls;
}
I expect it to get the expiration date. However it keeps saying:
java.sql.SQLException: no such column: 'SP_SELLBY_DATE'
Edit:
I changed the code to look like this:
public ArrayList<String> GetExpiredStock(){
Connection dbConnection = null;
ResultSet list = null;
ArrayList<String> ls = new ArrayList<String>();
LocalDate currentDate = LocalDate.now();
//System.out.println(today);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try {
dbConnection = DriverManager.getConnection("jdbc:sqlite:"+dbName+".db");
Statement Query_Statement = dbConnection.createStatement();
Query_Statement.setQueryTimeout(10);
list = Query_Statement.executeQuery("SELECT SP_SELLBY_DATE, STOCK_ID FROM STOCK_PURCHASE"); //this works
while (list.next()) {
try {
String da = list.getString("SP_SELLBY_DATE");
int id = list.getInt("STOCK_ID");
System.out.println("Executed on id = " + id);
LocalDate expDate = LocalDate.parse(da, formatter);
LocalDate monthAway = expDate.minusMonths(1);
System.out.println(currentDate);
if(currentDate.isAfter(monthAway)) {
ResultSet ids = Query_Statement.executeQuery("SELECT STOCK_NAME FROM STOCK WHERE STOCK_ID=" + id);
ls.add(ids.getString("STOCK_NAME") + "\t\t" +
da + "\t\t"+ getStockQuant(id,
currentDate));
}
}catch(SQLException e) {
System.err.println(e);
continue;
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
try {
if (dbConnection != null)
dbConnection.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return ls;
But it still fails after the first iteration
Your SQL query doesn't have the required column, add it :
SELECT SP_ENTRY_DATE, STOCK_ID, SP_SELLBY_DATE FROM STOCK_PURCHASE
I believe you query it list.getString("SP_SELLBY_DATE") twice in your loop, that should be root cause. Instead, you should use a variable when you get it to avoid to call it again as cursor has changed.
I am trying to get date in my database that have format like this "dd/MM/yyyy" and compare them to get latest date..
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me. Any suggestions? It seems like this should be an easy feat to accomplish.
from String last_updatedArr[]'s array result :
12/11/2015
12/11/2015
12/11/2015
12/11/2015
12/11/2015
13/11/2015
Method:
public String latestDate(){
String last_updated=null;
try {
String last_updatedDb=null;
String query = "SELECT Last_updated FROM Mattress";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs= pst.executeQuery();
String last_updatedArr[]=new String[100];
while(rs.next()){
int i = 0;
last_updatedDb=rs.getString("Last_updated");
System.out.println(last_updatedDb);
last_updatedArr[i]=last_updatedDb;
i++;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date date1,date2;
for(int i =0;i<last_updatedArr.length;i++){
date1 = (java.sql.Date)sdf.parse(last_updatedArr[i]);
date2 = (java.sql.Date)sdf.parse("1/1/2010");
if(date1.after(date2)){
//Date1 is after Date2
last_updated= sdf.format(date1);
}
if(date1.before(date2)){
//Date1 is before Date2
last_updated= sdf.format(date2);
}
if(date1.equals(date2)){
//Date1 is equal Date2
last_updated= sdf.format(date1);
}
}
} catch (ParseException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return last_updated;
}
Your loop resets i on every iteration. Move the declaration of i in your while loop. Or just use a for loop. Like,
for(int i = 0; rs.next(); i++) {
last_updatedDb = rs.getString("Last_updated");
System.out.println(last_updatedDb);
last_updatedArr[i] = last_updatedDb;
}
or something like,
int i = 0;
while(rs.next()){
// int i = 0;
last_updatedArr[i] = rs.getString("Last_updated");
System.out.println(last_updatedArr[i]);
i++;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date date1,date2;
// reuse i from while loop...
for(i = 0; i < last_updatedArr.length; i++){
I am trying to insert date into mysql. The field is of date type
but when I select a date from datepicker and insert it into database,it takes a random date..not getting where the problem is..
the code is as follow:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date d = null;
Date parsed = null;
try {
parsed = format.parse(request.getParameter("dt"));
System.out.println(parsed);
if (parsed != null) {
d = new java.sql.Date(parsed.getTime()); //parsed.getTime(
System.out.println(d);
} else {
d = new java.sql.Date(new Date().getTime());
}
} catch (ParseException e1) {
e1.printStackTrace();
}
String nature = request.getParameter("call_nature");
String name = request.getParameter("c_name");
String cat = request.getParameter("call").toString();
String num = request.getParameter("phone_no");
String street = request.getParameter("streetno").toString();
String rbut = request.getParameter("c_room");
String val = request.getParameter("hidd");
String zone = request.getParameter("combo1").toString();
String div = request.getParameter("combo2");
String hrs = request.getParameter("hr1");
String mns = request.getParameter("mn1");
String am = request.getParameter("ap1");
String occup = request.getParameter("occu");
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionurl = "jdbc:mysql://localhost:3306/fms";
String user = "root";
String pass = "root";
Connection con = DriverManager.getConnection(connectionurl, user, pass);
String sql = "insert into fire_reg values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prst = con.prepareStatement(sql);
prst.setString(1, nature);
prst.setString(2, cat);
prst.setString(3, name);
prst.setString(4, num);
prst.setString(5, val);
prst.setString(6, street);
prst.setDate(7, d);
prst.setString(8, rbut);
prst.setString(9, zone);
prst.setString(10, div);
prst.setString(11, hrs);
prst.setString(12, mns);
prst.setString(13, am);
prst.setString(14, occup);
if (prst.executeUpdate() == 1) {
request.setAttribute("loc", street);
//System.out.println(street);
request.setAttribute("phone", num);
request.setAttribute("calltypee", cat);
request.setAttribute("zonee", zone);
RequestDispatcher rd = request.getRequestDispatcher("FMS14_DelhiRegMap.jsp");
rd.forward(request, response);
}
} catch (Exception e) {
System.out.println(e);
}
I've got a method, that returns the value of a ResultSet query via a date object. The snag is that, in my output, it only returns the last value in the particular column. How do i go about this?
public Date getTime(){
Date date = null;
DateFormat format;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM error_log WHERE service_source = 'Billbox' ");
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
}
con.close();
} catch (Exception ex) {
Logger.getLogger(LogDB.class.getName()).log(
Level.SEVERE, null, ex);
}
return date;
}
Then in my main method:
public static void main(String args[]){
TestA ea = new TestA();
Date ss = ea.getTime();
System.out.println(ss);
}
But this only returns the last value in my query. how can i print out other (the olders) along with it?
You need to fill a list of dates from your query results. Try this :
public List<Date> getTime(){
List<Date> dates = new ArrayList<Date>();
DateFormat format;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM error_log WHERE service_source = 'Billbox' ");
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
dates.add((Date)format.parse(ds));
}
con.close();
} catch (Exception ex) {
Logger.getLogger(LogDB.class.getName()).log(
Level.SEVERE, null, ex);
}
return dates;
}
Because of the while loop you asign to date the last value.
Change your method as
public List<Date> getTime(){
You can try
List<Date> dates = new ArrayList<Date>();
and then inside your while loop;
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
dates.put(date);
}
return dates;
just:
List<Date> lDateDb = new ArrayList<Date>();
while (result.next()) { //retrieve data
String ds = result.getString("error_date");
format = new SimpleDateFormat("M/d/yyyy H:m:s a");
date = (Date)format.parse(ds);
lDateDb.add(date);
}
return lDateDb;
change return type of getTime to List<Date> and change the main to:
public static void main(String args[]){
TestA ea = new TestA();
List<Date> lAllDate = ea.getTime();
for (Date lDate : lAllDate)
System.out.println(lDate );
}
the error occur near the parsing of proj_close_date.( java.text.ParseException: Unparseable date: "09/09/2010" )
i am reading project_close_date value from database which is in string format. i want convert it in to date format to find that, is proj_close_date present between from_date and to_date
public ArrayList viewAllCustProj1(String frm_date,String to_date,String cust,String proj)
{
ArrayList list= new ArrayList();
try
{
String strCust="";
String strproj="";
if(!cust.equalsIgnoreCase("ALL") && !cust.equals(null))
{
strCust="and customer_code='"+cust+"'";
}
if(!proj.equalsIgnoreCase("ALL") && !proj.equals(null))
{
strproj="and project_code='"+proj+"'";
}
if(cust.equalsIgnoreCase("ALL") && !proj.equalsIgnoreCase("ALL"))
{
}
else
{
stmt=conn.prepareStatement("select customer_code from mst_customer where visible=1 "+strCust+" and category='EU' and multiple_project=0");
rs=stmt.executeQuery();
while(rs.next())
{
reportBean bean=new reportBean();
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code("");
list.add(bean);
}
rs.close();
stmt.close();
}
System.out.println(" select customer_code,project_code,proj_close_date,added_on from mst_project where visible=1 "+strCust+" "+strproj+"");
stmt=conn.prepareStatement("select customer_code,project_code,proj_close_date,added_on from mst_project where visible=1 "+strCust+" "+strproj+"");
rs=stmt.executeQuery();
while(rs.next())
{
reportBean bean=new reportBean();
String proj_close_date=rs.getString(3);
String added_on=rs.getString(4);
DateFormat myDateFormat = new SimpleDateFormat("MM-dd-yyyy");
DateFormat myDateFormat1= new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date myDate1 = null;
Date myDate2 = null;
Date myDate3 = null;
Date myDate4 = null;
Date myDate5 = null;
try
{
if(proj_close_date==null || proj_close_date.trim().equals("") || proj_close_date=="NULL")
{
System.out.println("\n ****** In IF Loop ");
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
else
{
System.out.println("\n ****** In Else Loop ");
myDate1 = myDateFormat.parse(proj_close_date);
myDate2 = myDateFormat.parse(frm_date);
myDate3 = myDateFormat.parse(to_date);
myDate5 = myDateFormat1.parse(added_on);
//myDate4 = myDateFormat.format(myDate5);
System.out.println("Project Code ---->"+rs.getString(2));
System.out.println("Proj_close_date ------>"+myDate1);
System.out.println("From Date ---->"+myDate2);
System.out.println("to Date ---->"+myDate3);
//System.out.println("Added_on --->"+myDate4);
System.out.println("Added_on 1 ie Date 5 ---->"+myDate5);
if(myDate1.after(myDate2) && myDate1.before(myDate3)) // means --> if(proj_close_date.after(frm_date) && proj_close_date.before(to_date))
{
if(myDate1.after(myDate4)) // means --> if(proj_close_date.after(added_on))
{
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
else
{
bean.setCust_code(rs.getString("customer_code"));
bean.setProject_code(rs.getString("project_code"));
list.add(bean);
}
}//if
}//else
}//try
catch (ParseException e)
{
System.out.println("Invalid Date Parser Exception ");
e.printStackTrace();
}
}
rs.close();
stmt.close();
}
catch(SQLException sex)
{
sex.printStackTrace();
}
finally
{
closeConnection();
}
return list;
}
Change this line
DateFormat myDateFormat = new SimpleDateFormat("MM-dd-yyyy");
to this:
DateFormat myDateFormat = new SimpleDateFormat("MM/dd/yyyy");
However, it's quite unclear why you get all the values as strings, perhaps you should consider dedicated ResultSet methods such as getDate or getTimeStamp.
As another side remark I'd like to mention that building SQL queries by concatenation should be avoided -- you should generate queries with ? placeholders, and then set the parameters on your PreparedStatement.