Not getting total records from the database - java

I have 4 records in my database table, but i am getting only one record from the function. please check my code once. When i call the getMaterialTransferRecords() function inside this function i have another function getMaterialUnit(). I am not able to find the solution. Please any one help me.
This is the query i am executing in my sqlyog. please check it once
Above is my query and below is the result.
This is how i am calling the function.
// Fetch Data from User Table
int startPageIndex = Integer.parseInt(request.getParameter("jtStartIndex"));
int recordsPerPage = Integer.parseInt(request.getParameter("jtPageSize"));
String jtSorting = request.getParameter("jtSorting");
MaterialTransferUtils utils = new MaterialTransferUtils();
//System.out.println("Cash Purchases Start Page Index:"+startPageIndex+" recordsPerPage:"+recordsPerPage);
if(jtSorting != null)
{
jtSorting = jtSorting.replaceAll("material_destn_code", "material_destn_code");
jtSorting = jtSorting.replaceAll("date", "transferred_on");
}
// Fetch Data from Cash Memo Table
mtList = utils.getMaterialTransferRecords(startPageIndex, recordsPerPage,jtSorting);
Please check the code once.
public List<MaterialTransferBean> getMaterialTransferRecords(int startPageIndex, int recordsPerPage,String jtSorting)
{
List<MaterialTransferBean> list = new ArrayList<MaterialTransferBean>();
con=com.s2s.bssb.database.ConnectionFactory.getConnection();
MaterialTransferBean mtbean = null;
String sortStr = "material_destn_code DESC";
if(null != jtSorting)
sortStr = jtSorting;
String query = "SELECT sno,material_loc_code,transferred_on,mr_no,do_no,material_destn_code,material_id,quantity,unit_price, "
+ "gst,remarks FROM material_transfer ORDER BY "+sortStr+" LIMIT "+recordsPerPage+" offset "+startPageIndex+"";
System.out.println(query);
if(con!=null){
try{
ps=con.prepareStatement(query);
rs=ps.executeQuery();
while(rs.next()){
MaterialTransferBean bean = new MaterialTransferBean();
bean.setSno(rs.getInt("sno"));
bean.setMaterial_loc_code(rs.getString("material_loc_code"));
bean.setDate(rs.getDate("transferred_on"));
bean.setMr_no(rs.getString("mr_no"));
bean.setDo_no(rs.getString("do_no"));
bean.setMaterial_destn_code(rs.getString("material_destn_code"));
bean.setQuantity(rs.getDouble("quantity"));
bean.setUnit_price(rs.getDouble("unit_price"));
bean.setAmount(rs.getDouble("quantity")*rs.getDouble("unit_price"));
bean.setGst(((rs.getDouble("quantity")*rs.getDouble("unit_price"))*(rs.getDouble("gst")))/100);
bean.setTtl_amount((rs.getDouble("quantity")*rs.getDouble("unit_price"))+(((rs.getDouble("quantity")*rs.getDouble("unit_price"))*(rs.getDouble("gst")))/100));
bean.setRemarks(rs.getString("remarks"));
mtbean = new MaterialTransferBean();
mtbean = getMaterialUnit(rs.getInt("material_id"));
bean.setMaterial(mtbean.getMaterial());
bean.setUnit(mtbean.getUnit());
list.add(bean);
}
rs.close();
com.s2s.bssb.database.ConnectionDB.close(con);
com.s2s.bssb.database.ConnectionDB.close(ps, con);
}catch(SQLException sql_ex){
sql_ex.printStackTrace();
}
}else{
System.out.println("Connection Not Created");
}
return list;
}
public MaterialTransferBean getMaterialUnit(int material_id){
MaterialTransferBean bean = null;
con=com.s2s.bssb.database.ConnectionFactory.getConnection();
String query = "select material,unit from materials where id=?";
if(con!=null){
try{
ps=con.prepareStatement(query);
ps.setInt(1, material_id);
rs=ps.executeQuery();
while(rs.next()){
bean = new MaterialTransferBean();
bean.setMaterial(rs.getString("material"));
bean.setUnit(rs.getString("unit"));
}
}catch(SQLException sql_ex){
sql_ex.printStackTrace();
}
}
return bean;
}

Related

Validating Text fields in Java not working?

I am creating an SQL that stores information about customers, and want all the customers to have unique contact numbers, essentially as an identifier for themselves. However my validation for my SQL seems to run even if the number already exists within the SQL, and am unsure of what is going wrong.
public static boolean uniqueValidation(String contactNum){
Connection c = null;
Statement stmt = null;
boolean result = true;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:custInfo.db"); //this is telling the code where to retrieve the data from that it is looking for.
stmt = c.createStatement();
String sql = "SELECT rowid AS isFound FROM CUSTINFO WHERE CONTACTNUMBER LIKE "+contactNum+""; //collecting a rowid from custinfo, if the number is found anywhere
ResultSet rs = stmt.executeQuery(sql);
String compareString = rs.getString("isFound"); //setting the value from the resultset of rowid to comparestring
if(!compareString.isEmpty()){ //if there is a value return false
result = false;
}else{
result = true; //else return true as there is no value
}
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return result;
}

ResultSet not open although i have only one at a time

I know many questions were asked before for this issue but for this situations I can't find an answer.
This is my code:
private Collection<Coupon> getCouponsMain(Company company, String filters) throws DAOException
{
String sql = null;
if (filters != null)
{
sql = "SELECT couponsystem.coupon.* FROM couponsystem.company_coupon LEFT JOIN couponsystem.coupon ON "
+ "couponsystem.company_coupon.COUPON_ID = couponsystem.coupon.ID WHERE couponsystem.company_coupon.COMP_ID = ? AND ?";
}
else
{
sql = "SELECT couponsystem.coupon.* FROM couponsystem.company_coupon LEFT JOIN couponsystem.coupon ON "
+ "couponsystem.company_coupon.COUPON_ID = couponsystem.coupon.ID WHERE couponsystem.company_coupon.COMP_ID = ?";
}
try (Connection con = pool.OpenConnection(); PreparedStatement preparedStatement = con.prepareStatement(sql);)
{
// query command
preparedStatement.setLong(1, company.getId());
if (filters != null)
{
preparedStatement.setString(2, filters);
}
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
{
CouponDBDAO couponDao = new CouponDBDAO();
rs.previous();
return couponDao.BuildCoupons(rs);
}
else
{
return null;
}
}
catch (SQLException | NullPointerException e)
{
throw new DAOException("Failed to retrieve data for all coupons" + e.getMessage());
}
}
I think the query itself is not the important issue here but, once I use next() for the ResultSet, I get the error:
java.sql.SQLException: Operation not allowed after ResultSet closed"
This usually happened when using two rs for same statement, this is not the case this time.
Due to many issues with previous method and BuildCoupons(rs) issue, also this part does not work properly for the same reason:
#Override
public Company getCompany(long id) throws DAOException
{
String sql = "SELECT * FROM couponsystem.company WHERE ID = ?";
try (Connection con = pool.OpenConnection(); PreparedStatement preparedStatement = con.prepareStatement(sql);)
{
// query command
preparedStatement.setLong(1, id);
// query execution
ResultSet rs = preparedStatement.executeQuery();
Company comp = new Company();
if (rs.next())
{
//Fill customer object from Customer table
comp.setId(rs.getLong("ID"));
comp.setCompName(rs.getString("COMP_NAME"));
comp.setPassword(rs.getString("PASSWORD"));
comp.setEmail(rs.getString("EMAIL"));
comp.setCoupons(comp.getCoupons());
}
else
{
comp = null;
}
return comp;
}
catch (SQLException e)
{
throw new DAOException("Failed to retrieve data for customer id: " + id);
}
}
BTW - working with MySQL and insert, update and delete queries are working properly so there not issue with the connection to the db
Another update -
Once i replace it to regular statement, it's working but of course i'm losing all the advantages of prepared statement
Like i said i create new code in order to isolate the big program
This is the code:
public class testState
{
public static void main(String[] args) throws SQLException
{
DBDAO pool = DBDAO.getInstance();
String sql = "SELECT ID FROM couponsystem.company WHERE COMP_NAME = ? AND PASSWORD = ?";
String compName = "t";
String password = "t";
pool.CreatePool();
Connection con = pool.OpenConnection();
PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setString(1, compName);
preparedStatement.setString(2, password);
preparedStatement.executeQuery();
ResultSet rs = preparedStatement.executeQuery();
System.out.println("rs status: " + rs.isClosed());
if (rs.next())
{
System.out.println("log-in was successfuly performed");
System.out.println(rs.getLong(1));
System.out.println("hjhjh");
}
else
{
System.out.println("-1");
}
rs.close();
preparedStatement.close();
con.close();
pool.CloseConnection();
}
}
Problem was solved,
this is the problem:
sql = "SELECT couponsystem.coupon.* FROM couponsystem.company_coupon LEFT JOIN couponsystem.coupon ON "
+ "couponsystem.company_coupon.COUPON_ID = couponsystem.coupon.ID WHERE couponsystem.company_coupon.COMP_ID = ? AND ?";
the second ? is illegal, but the exception is ResultSet closed and not query issue
the problem is you are trying to go back to the previous record in the result set which is not possible.
learn about scrollable resultset and make it insensitive, once you use this you can go back to the previous record by using rs.previous()
ResultSet.TYPE_SCROLL_INSENSITIVE

how to check if id in mysql already exists with java

I want to check if my id is already exist or not:
sql2 = "SELECT stid FROM student";
stmt.executeUpdate(sql2);
rs = stmt.executeQuery(sql2);
while(rs.next()){
id = rs.getString("stid");
if(tf_insert1.equals(id)){
JOptionPane.showMessageDialog(null, "ID is already exists");
id = tf_insert1.getText();
name = tf_insert2.getText();
address = tf_insert3.getText();
gender = tf_insert4.getText();
ip = tf_insert5.getText();
tf_insert1.setText(id);
tf_insert2.setText(name);
tf_insert3.setText(address);
tf_insert4.setText(gender);
tf_insert5.setText(ip);
Any idea to solve this thing???
Please check this. I have modified code in 2 parts.
One for checking the id exists or not
and another for insert section.
Hope it will help to solve your issue.
private void yourFunction(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"SELECT stid FROM student where stid = ?");
stmt.setLong(1, Long.parseLong(stid.getText()));
ResultSet rs=stmt.executeQuery();
bool recordAdded = false;
while(!rs.next()){
recordAdded = true;
}
if( recordAdded ){
// your code for insertion.
}else{
JOptionPane.showMessageDialog(null, "ID is already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}

error in inserting data to database

Here's my code for createFood DA so that can insert to database. However , there is a nullPointerException at
pstmt.setString(2, food.getFoodName());
public static int createFood(Food food) {
// declare local variables
int orderID ;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - establish connection to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "INSERT INTO orderitems (orderId, foodName, foodPrice, quantity,) VALUES(?,?,?,? )";
pstmt = (PreparedStatement) db.getPreparedStatement(dbQuery);
orderID = getNextOrderId();
// step 3 - to insert record using executeUpdate method
try {
pstmt.setInt(1,orderID );
pstmt.setString(2, food.getFoodName());
pstmt.setDouble(3 ,food.getFoodPrice());
pstmt.setInt(4, food.getQuantity());
if (pstmt.executeUpdate() == 1)
return orderID;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return -1;
}
This is the code when i click on "orders".
private void actionPerformedOrder() {
//retrieve user input
String numPax = (String) cbNoPax.getSelectedItem();
String tableNo= (String)cb_tableno.getSelectedItem();
java.util.Date utilDate = new java.util.Date();
Date orderDate = new Date(utilDate.getTime());
System.out.println("Date " + orderDate);
orders = new Orders(Integer.parseInt(tableNo),Integer.parseInt(numPax), (java.sql.Date) orderDate, totalAmount);
int orderID = OrdersDA.createOrders(orders);
OrderItems od;
for (Food fd: foodList) {
od = new OrderItems(orderID, fd.getFoodName(), fd.getQuantity(), fd.getFoodPrice());
FoodDA.createFood(food);
}
I still cannot figure out the error. Anyone knows where went wrong ? Much help will be appreciated.
You have passed createFood() method food variable which i cant see declare anywhere
try
createFood(fd) according to your code.

How do I abstract my business logic and object defintions away from my database access code?

So I have a database with 2 tables - Workflows and WorkflowSteps I want to use the rows stored there to create objects in java BUT the catch is that I want to have my database code separated from my application code. From one point onwards - when Workflow/WorkflowSteps objects are create the rest of the application will not have to worry about DB access. So here is what I have:
public Workflow getPendingWorkflowId() {
int workflowid = -1;
Statement statement = null;
ResultSet rs = null;
try {
statement = con.createStatement();
rs = statement.executeQuery("SELECT id FROM xxx.workflows WHERE status = 'NOT-YET-STARTED' LIMIT 1");
while (rs.next()) {
workflowid = rs.getInt("id");
}
statement.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error fetching workflows id");
}
return new Workflow(workflowid);
}
Each workflow object has a List to store the steps that pertain to a particular Workflow and then each WorkflowStep has a Map which is used to store data taken from a 3rd table:
public List<WorkflowStep> getUnworkedStepsByWFId(int id) {
//can be changed
ArrayList<WorkflowStep> steps = new ArrayList<WorkflowStep>();
Statement statement = null;
ResultSet rs = null;
try {
statement = con.createStatement();
rs = statement.executeQuery("SELECT * FROM `workflow_steps` WHERE `workflow_id` =" + id + " AND status = 'NOT-YET-STARTED'");
while (rs.next()) {
steps.add(new WorkflowStep(rs.getInt(1), rs.getInt(3), rs.getInt(4)));
}
statement.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error fetching workflows id");
}
return steps;
}
And here is the query for the 3rd table:
public Map getParametersForStep(int workflowId, int workstepPos) {
Statement statement = null;
ResultSet rs = null;
Map<String, String> hMap = new HashMap<String, String>();
try {
statement = con.createStatement();
//MIGHT BE WRONG
rs = statement.executeQuery("SELECT wf.id AS workflowID, ws_steps.id AS workflowStepsID, name, param_value, pathname FROM workflows AS wf INNER JOIN workflow_steps AS ws_steps ON wf.id = ws_steps.workflow_id INNER JOIN ws_parameters ON ws_parameters.ws_id = ws_steps.id INNER JOIN submodule_params ON submodule_params.id = ws_parameters.sp_id AND wf.id =" + workflowId + " AND ws_steps.workflow_position =" + workstepPos);
String paramName = null;
String paramValue = null;
while (rs.next()) {
paramName = rs.getString("name");
if (rs.getString("param_value") == null) {
paramValue = rs.getString("pathname");
} else {
paramValue = rs.getString("param_value");
}
hMap.put(paramName, paramValue);
}
statement.close();
rs.close();
return hMap;
} catch (SQLException ex) {
Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error fetching workflow step parameters names");
}
return Collections.emptyMap();
}
Having this code in mind I end up with the following "procedure" to initialize a Workflow with all its WorkflowSteps and their Parameters:
Workflow wf = db.getPendingWorkflowId();
wf.initSteps(db.getUnworkedStepsByWFId(wf.getId()));
Iterator<WorkflowStep> it = wf.getSteps();
while(it.hasNext()) {
WorkflowStep step = it.next();
step.setParameters(db.getParametersForStep(wf.getId(), step.getPosInWorkflow()));
}
I think I have a good level of decoupling but I wonder if this can be refactored somehow - for example probably move the step.setParameters to a method of the WorkflowStep class but then I would have to pass a reference to the database connection (db) to a WorkflowStep object but in my view this will break the decoupling? So how would you people refactor this code?
It seems that you are rolling your own ORM. My suggestion would be to use one of existing ones like Hibernate.
This is the function of an Object Relational Mapper. It serves to abstract your DB access away from your business model. In fact, used properly, an ORM library allows you to write no database code at all.

Categories

Resources