Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I keep getting this error whenever I attempt to run a specific jsp on my project
I've done everything that i can think of (including recreating the database it needs, checking and rechecking the lines that I assume has the fault, line #165 of Projectbean.java, more specifically the prepared statement part of the public int rowCount() function)
If someone could please point me to the right direction, it will be greatly appreciated.
Projectservlet.java:
import project.Projectbean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author REY
*/
#WebServlet(name = "Projectservlet", urlPatterns = {"/Projectservlet"})
public class Projectservlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Projectservlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Projectservlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String option=request.getParameter("menu");
if(option == null || option.equals("menu"))
{
RequestDispatcher dr = request.getRequestDispatcher("Menu.jsp");
dr.forward(request, response);
}
else if(option.equals("stud"))
{
RequestDispatcher dr = request.getRequestDispatcher("Student.jsp");
dr.forward(request, response);
}
else if(option.equals("book"))
{
RequestDispatcher dr = request.getRequestDispatcher("Book.jsp");
dr.forward(request, response);
}
else if(option.equals("cat"))
{
RequestDispatcher dr = request.getRequestDispatcher("Category.jsp");
dr.forward(request, response);
}
else if(option.equals("Borrow"))
{
RequestDispatcher dr = request.getRequestDispatcher("Borrow.jsp");
dr.forward(request, response);
}
else if(option.equals("Return"))
{
RequestDispatcher dr = request.getRequestDispatcher("Return.jsp");
dr.forward(request, response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String option = request.getParameter("option");
//STUDENT CONTROLLER
if (option.equals("Add Student"))
{
RequestDispatcher dr = request.getRequestDispatcher("AddStudent.jsp");
dr.include(request, response);
}
else if (option.equals("addedS"))
{
String id = request.getParameter("Studid");
int a = Integer.parseInt(id);
Projectbean addCustomer = new Projectbean();
addCustomer.setStudid(a);
addCustomer.setFname(request.getParameter("Fname"));
addCustomer.setLname(request.getParameter("Lname"));
addCustomer.setCourse(request.getParameter("Course"));
addCustomer.AddStudent();
RequestDispatcher dr = request.getRequestDispatcher("AddStudtConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Edit Student"))
{
RequestDispatcher dr = request.getRequestDispatcher("EditCustomer.jsp");
dr.include(request, response);
}
else if (option.equals("editS"))
{
String Studid = request.getParameter("edit");
request.setAttribute("Studid", Studid);
RequestDispatcher dr = request.getRequestDispatcher("EditedStudent.jsp");
dr.include(request, response);
}
else if (option.equals("editedC"))
{
Projectbean edit = new Projectbean();
int id = Integer.parseInt(request.getParameter("Studid"));
edit.setStudid(id);
edit.setFname(request.getParameter("Fname"));
edit.setLname(request.getParameter("Lname"));
edit.setCourse(request.getParameter("Course"));
edit.EditStudent();
RequestDispatcher dr = request.getRequestDispatcher("EditStudConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Delete Student"))
{
RequestDispatcher dr = request.getRequestDispatcher("DeleteStudent.jsp");
dr.include(request, response);
}
else if (option.equals("deleteS"))
{
String ID = request.getParameter("delete");
int custID = Integer.parseInt(ID);
Projectbean delete = new Projectbean();
delete.DeleteStudent(custID);
RequestDispatcher dr = request.getRequestDispatcher("DeleteStudConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Search Student"))
{
RequestDispatcher dr = request.getRequestDispatcher("SearchStudent.jsp");
dr.include(request, response);
}
else if (option.equals("searchS"))
{
String search = request.getParameter("search");
request.setAttribute("search", search);
RequestDispatcher dr = request.getRequestDispatcher("SearchedStudent.jsp");
dr.include(request, response);
}
//CATEGORY CONTROLLER
else if (option.equals("Add Category"))
{
RequestDispatcher dr = request.getRequestDispatcher("AddCategory.jsp");
dr.include(request, response);
}
else if (option.equals("addedCat"))
{
String id = request.getParameter("Catid");
int a = Integer.parseInt(id);
Projectbean addCategory = new Projectbean();
addCategory.setCatid(a);
addCategory.setCatname(request.getParameter("Catname"));
addCategory.AddCategory();
RequestDispatcher dr = request.getRequestDispatcher("AddCatConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Edit Category"))
{
RequestDispatcher dr = request.getRequestDispatcher("EditCategory.jsp");
dr.include(request, response);
}
else if (option.equals("editCat"))
{
String catID = request.getParameter("catedit");
request.setAttribute("Catid", catID);
out.println (catID);
RequestDispatcher dr = request.getRequestDispatcher("EditedCategory.jsp");
dr.forward(request, response);
}
else if (option.equals("editedCat"))
{
Projectbean editcat = new Projectbean();
int id = Integer.parseInt(request.getParameter("Catid"));
editcat.setCatid(id);
editcat.setCatname(request.getParameter("Catname"));
editcat.EditCategory();
RequestDispatcher dr = request.getRequestDispatcher("EditCatConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Delete Category"))
{
RequestDispatcher dr = request.getRequestDispatcher("DeleteCategory.jsp");
dr.include(request, response);
}
else if (option.equals("delCat"))
{
String ID = request.getParameter("catdelete");
int Catid = Integer.parseInt(ID);
Projectbean catdelete = new Projectbean();
catdelete.DeleteCategory(Catid);
RequestDispatcher dr = request.getRequestDispatcher("DeleteCatConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Search Category"))
{
RequestDispatcher dr = request.getRequestDispatcher("SearchCategory.jsp");
dr.include(request, response);
}
else if (option.equals("searchCat"))
{
String search = request.getParameter("search");
request.setAttribute("search", search);
RequestDispatcher dr = request.getRequestDispatcher("SearchedCategory.jsp");
dr.include(request, response);
}
//PRODUCT CONTROLLER
else if (option.equals("Add Book"))
{
RequestDispatcher dr = request.getRequestDispatcher("AddBook.jsp");
dr.include(request, response);
}
else if (option.equals("addedBook"))
{
String id = request.getParameter("Bookid");
String Catid = request.getParameter("edit");
int catID = Integer.parseInt (Catid);
int Bookid = Integer.parseInt(id);
//int numavail = Integer.parseInt(request.getParameter("availNo"));
//double price = Double.parseDouble(request.getParameter("prodPrice"));
Projectbean addProduct = new Projectbean();
addProduct.setBookid(Bookid);
addProduct.setTitle(request.getParameter("Title"));
addProduct.setAuthor(request.getParameter("Author"));
//addProduct.setProdAvail(numavail);
//addProduct.setProdPrice(price);
addProduct.setCatid(catID);
addProduct.AddBook();
RequestDispatcher dr = request.getRequestDispatcher("AddBookConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Edit Book"))
{
RequestDispatcher dr = request.getRequestDispatcher("EditBook.jsp");
dr.include(request, response);
}
else if (option.equals("editBook"))
{
String Bookid = request.getParameter("prodedit");
request.setAttribute("Bookid", Bookid);
out.println (Bookid);
RequestDispatcher dr = request.getRequestDispatcher("EditedBook.jsp");
dr.forward(request, response);
}
else if (option.equals("editedBook"))
{
Projectbean editprod = new Projectbean();
int id = Integer.parseInt(request.getParameter("Bookid"));
//int avail = Integer.parseInt (request.getParameter("prodavail"));
double price = Double.parseDouble(request.getParameter("prodprice"));
int catID = Integer.parseInt(request.getParameter("category"));
editprod.setBookid(id);
editprod.setTitle(request.getParameter("Title"));
editprod.setAuthor(request.getParameter("Author"));
//editprod.setProdAvail(avail);
//editprod.setProdPrice(price);
editprod.setCatid(catID);
editprod.EditBook();
RequestDispatcher dr = request.getRequestDispatcher("EditBookConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Delete Book"))
{
RequestDispatcher dr = request.getRequestDispatcher("DeleteBook.jsp");
dr.include(request, response);
}
else if (option.equals("delBook"))
{
String ID = request.getParameter("bookdel");
int prodID = Integer.parseInt(ID);
Projectbean catdelete = new Projectbean();
catdelete.DeleteBook(prodID);
RequestDispatcher dr = request.getRequestDispatcher("DeleteBookConfirm.jsp");
dr.include(request, response);
}
else if (option.equals("Search Book"))
{
RequestDispatcher dr = request.getRequestDispatcher("SearchBook.jsp");
dr.include(request, response);
}
else if (option.equals("searchBook"))
{
String id = request.getParameter("category");
String search = request.getParameter("search");
request.setAttribute("Catid",id);
request.setAttribute("search", search);
RequestDispatcher dr = request.getRequestDispatcher("SearchedBook.jsp");
dr.include(request, response);
}
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Projectbean.java
package project;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Projectbean {
private Connection con;
//student
int Studid;
String Fname;
String Lname;
String Course;
//book
int Bookid;
String Title;
String Author;
String Dborrowed;
String Dreturned;
int Fee;
//Category
int Catid;
String Catname;
//student setters
public void setStudid (int id)
{
Studid = id;
}
public void setFname (String val)
{
Fname = val;
}
public void setLname (String val)
{
Fname = val;
}
public void setCourse (String val)
{
Course = val;
}
//student getters
public int getStudid ()
{
return Studid ;
}
public String getFname ()
{
return Fname ;
}
public String getLname ()
{
return Lname ;
}
public String getCourse ()
{
return Course ;
}
//book setters
public void setBookid (int id)
{
Bookid = id;
}
public void setTitle (String val)
{
Title = val;
}
public void setAuthor (String val)
{
Author = val;
}
public void setDborrowed (String val)
{
Dborrowed = val;
}
public void setDreturned (String val)
{
Dreturned = val;
}
public void setFee (int fee)
{
Fee = fee;
}
//book getters
public int getBookid ()
{
return Bookid ;
}
public String getTitle ()
{
return Title ;
}
public String getAuthor ()
{
return Author ;
}
public String getDborrowed ()
{
return Dborrowed ;
}
public String getDreturned ()
{
return Dreturned ;
}
public int getFee ()
{
return Fee ;
}
//Category setters
public void setCatid (int id)
{
Catid = id ;
}
public void setCatname(String val)
{
Catname = val;
}
//Category getters
public int getCatid()
{
return Catid;
}
public String getCatname()
{
return Catname;
}
public Projectbean(){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/final",
"", "");
}catch(Exception e){
System.out.println("Exception" + e);
}
}
//student
public ResultSet GetStudent() throws SQLException, Exception{
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.STUDENT");
return rs;
}
//set student id
public int rowCount() throws SQLException{
PreparedStatement st= con.prepareStatement("SELECT STUDENTID FROM APP.STUDENT");
ResultSet rs = st.executeQuery();
//get the number of rows from the result set
int count = 0;
while (rs.next()){
count = rs.getInt(1);
}
return count;
}
//get specific student
public void GetSpecificStudent (String StudID) throws SQLException, Exception{
int id = Integer.parseInt(StudID);
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.STUDENT WHERE STUDID="+id+" ");
rs.next();
this.Studid = id;
Fname = rs.getString("FIRSTNAME");
Lname = rs.getString ("LASTNAME");
Course = rs.getString("COURSE");
}
//Add Student
public void AddStudent(){
String read = "insert into APP.STUDENT (STUDID,FIRSTNAME,LASTNAME,COURSE) values(?,?,?,?)";
PreparedStatement addrec;
try {
addrec = con.prepareStatement(read);
addrec.setInt(1, Studid);
addrec.setString(2, Fname);
addrec.setString(3, Lname);
addrec.setString(4, Course);
addrec.execute();
}
catch (SQLException e){
System.out.println ("Exception " + e);
}
}
//edit student
public void EditStudent(){
String read = "Update APP.STUDENT set STUDID=?, FIRSTNAME=?, LASTNAME=?, COURSE=? where ID="+Studid;
PreparedStatement editRec;
try{
editRec = con.prepareStatement(read);
editRec.setInt (1,Studid);
editRec.setString(2,Fname);
editRec.setString(3,Lname);
editRec.setString(4,Course);
editRec.execute();
}
catch (SQLException e){
System.out.println ("Exception " + e);
}
}
//Delete student
public void DeleteStudent (int id) {
try
{
Statement s = con.createStatement();
String read= "Delete FROM APP.STUDENT where STUDID = "+id+"";
s.executeUpdate(read);
}
catch(SQLException e)
{
System.out.println(e);
}
}
//search student
public ResultSet SearchStudent(String search) throws SQLException, Exception{
String[] split = search.split("\\s+");
int count = split.length;
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.STUDENT WHERE FIRSTNAME= '"+split[0]+"' OR LASTNAME= '"+split[count-1]+"' ");
return rs;
}
//BOOK
public ResultSet GetBook() throws SQLException, Exception{
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.BOOK");
return rs;
}
//set book id
public int BookrowCount() throws SQLException{
PreparedStatement st= con.prepareStatement("SELECT BOOKID FROM APP.BOOK");
ResultSet rs = st.executeQuery();
//get the number of rows from the result set
int count = 0;
while (rs.next()){
count = rs.getInt(1);
}
return count;
}
//get specific book
public void GetSpecificBook (String BookID) throws SQLException, Exception{
int id = Integer.parseInt(BookID);
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.BOOK WHERE custID="+id+" ");
rs.next();
this.Bookid = id;
Title = rs.getString("TITLE");
Author = rs.getString ("AUTHOR");
Dborrowed = rs.getString("DATEBORROWED");
Dreturned = rs.getString("DATERETURNED");
Fee = rs.getInt("BORROWERSFEE");
}
//Add book
public void AddBook(){
String read = "insert into APP.BOOK (BOOKID,TITLE,AUTHOR,CATEGORYID) values(?,?,?)";
PreparedStatement addrec;
try {
addrec = con.prepareStatement(read);
addrec.setInt(1, Bookid);
addrec.setString(2, Title);
addrec.setString(3, Author);
addrec.setInt(4, Catid);
addrec.execute();
}
catch (SQLException e){
System.out.println ("Exception " + e);
}
}
//edit book
public void EditBook(){
String read = "Update APP.BOOK set BOOKID=?, TITLE=?, AUTHOR=?, CATEGORYID=? where BOOKID="+Bookid;
PreparedStatement editRec;
try{
editRec = con.prepareStatement(read);
editRec.setInt (1,Bookid);
editRec.setString(2,Title);
editRec.setString(3,Author);
editRec.setInt(4,Catid);
editRec.execute();
}
catch (SQLException e){
System.out.println ("Exception " + e);
}
}
//delete book
public void DeleteBook (int id) {
try
{
Statement s = con.createStatement();
String read= "Delete FROM APP.BOOK where BOOKID = "+id+"";
s.executeUpdate(read);
}
catch(SQLException e)
{
System.out.println(e);
}
}
//search book
public ResultSet SearchBook(String search) throws SQLException, Exception{
String[] split = search.split("\\s+");
int count = split.length;
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.book WHERE TITLE= '"+split[0]+"' OR AUTHOR= '"+split[count-1]+"' ");
return rs;
}
//CATEGORY
//Set Category ID
public int rowCountCat() throws SQLException{
PreparedStatement st= con.prepareStatement("SELECT CATEGORYID FROM APP.CATEGORY");
ResultSet rs = st.executeQuery();
//get the number of rows from the result set
int count1 = 0;
while (rs.next()){
count1 = rs.getInt(1);
}
return count1;
}
//Add Category
public void AddCategory (){
String read = "insert into APP.CATEGORY (CATEGORYID,CATEGORYNAME) values(?,?)";
PreparedStatement addrec;
try {
addrec = con.prepareStatement(read);
addrec.setInt(1, Catid);
addrec.setString(2, Catname);
addrec.execute();
}
catch (SQLException e){
System.out.println ("Exception " + e);
}
}
//Get List of Category
public ResultSet GetCategory () throws SQLException, Exception{
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.CATEGORY");
return rs;
}
//Get Specific Category
public void GetSpecificCategory (String catID) throws SQLException, Exception {
int id = Integer.parseInt(catID);
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.CATEGORY WHERE CATEGORYID="+id+" ");
rs.next();
this.Catid = id;
Catname = rs.getString("CATEGORYNAME");
}
//EDIT Category
public void EditCategory () {
String read = "Update APP.CATEGORY set CATEGORYID=?, CATEGORYNAME=? WHERE CATEGORYID="+Catid;
PreparedStatement editRec;
try{
editRec = con.prepareStatement(read);
editRec.setInt (1,Catid);
editRec.setString(2,Catname);
editRec.execute();
}
catch (SQLException e){
System.out.println ("Exception " + e);
}
}
//Delete Category
public void DeleteCategory (int id) {
try
{
Statement s = con.createStatement();
String read= "Delete FROM APP.CATEGORY where CATEGORYID = "+id+"";
s.executeUpdate(read);
}
catch(SQLException e)
{
System.out.println(e);
}
}
//Search Category
public ResultSet SearchCategory (String search) throws SQLException, Exception{
String[] split = search.split("\\s+");
int count = split.length;
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from APP.CATEGORY WHERE CATEGORYNAME= '"+split[0]+"' OR CATEGORYNAME= '"+split[count-1]+"' ");
return rs;
}
}
con may be mostly null at this point because there are no other candidates that can be null at this point
Related
A minimum runnable example of my project is above:
Shopping Cart and its Products; I need to save this aggregation in pure JDBC, without ORM, in the Database. Is it the proper way to save the product list to DB, passing to the shopping_cart_fk_id to each product and its DAOs?
MainClass
package ShoppingCartDAO;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args)
{
ShoppingCart shoppingCart = new ShoppingCart();
Integer choice = 0;
Scanner input = new Scanner(System.in);
do {
choice = 0;
System.out.print("Choose one option: \n");
System.out.print("1 - Register New Product \n");
System.out.print("0 - Exit And Save");
choice = input.nextInt();
switch (choice)
{
case 1:
new ShoppingCart().InsertInto(new ProductRegister().RegisterNewProduct());
break;
default:
System.out.print(" Invalid Option \n");
break;
}
} while (choice != 0);
new ShoppingCartDao().add(shoppingCart);
input.close();
}
}
ConnectionFactory
package ShoppingCartDAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class ShoppingCartDao{
public void add(ShoppingCart shoppingCart)
{
try
{
PreparedStatement pstmt = ConnectionFactory.getConnection().prepareStatement("Insert into shoppingCart (date) values (?)");
pstmt.setDate(1, new java.sql.Date(System.currentTimeMillis()));
pstmt.execute();
pstmt.close();
} catch(SQLException e)
{
throw new RuntimeException(e);
}
ProductDao productDAO = new ProductDao();
for(Product product : shoppingCart.getProduct()){
productDAO.add(product);
}
}
public Integer getCount()
{
Integer count;
try
{
Statement stmt = ConnectionFactory.getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS recordCount FROM shoppingcart");
rs.next();
count = rs.getInt(1);
rs.close();
stmt.close();
} catch(SQLException e)
{
throw new RuntimeException(e);
}
return count;
}
}
ShoppingCart Entity
public class ShoppingCart
{
Long id;
Date date;
ArrayList<Product>products = new ArrayList<Product>();
public ShoppingCart(){
this.date = new Date();
}
public void InsertInto(Product product){
products.add(product);
}
public Date getDate(){
return this.buyDate;
}
public ArrayList<Product>getProduct(){
return this.products;
}
}
Product Entity
public class Product
{
String name = new String();
Integer quantity = new Integer();
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setQuantity(Integer quantity){
this.quantity = quantity;
}
public Integer getQuantity(){
return this.quantity;
}
}
Shopping Cart DAO
package ShoppingCartDAO;
import java.util.ArrayList;
import java.util.Date;
public class ShoppingCart {
Long id;
Date date;
ArrayList<Product>products = new ArrayList<Product>();
public ShoppingCart(){
this.date = new Date();
}
public void InsertInto(Product product){
products.add(product);
}
public Date getDate(){
return this.date;
}
public ArrayList<Product>getProduct(){
return this.products;
}
public void addProduct(Product product) {
products.add(product);
}
}
ProductDAO
package ShoppingCartDAO;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ProductDao {
public void add(Product product)
{
try
{
String query = "Insert into product (fkShoppingCartId, name, quantity) values (?, ?, ?)";
PreparedStatement pstmt = ConnectionFactory.getConnection().prepareStatement(query);
pstmt.setLong(1, new ShoppingCartDao().getCount() + 1);
pstmt.setString(2, product.getName());
pstmt.setInt(3, product.getQuantity());
pstmt.execute();
pstmt.close();
}
catch(SQLException e)
{
throw new RuntimeException(e);
}
}
You have a Java model for your data, what database schema do you need to store it?
It's pretty obvious for the simple types like numbers and strings; for the List of products in your ShoppingCart, I assume you want to conserve the order of the Products in you ShoppingCart. I also assume that a Product is in fact an item in a ShoppingCart since it has a quantity field; so a Product has no existence of it's own: it's a part of a ShoppingCard.
With these assumptions, I can represent the Java model in the database with two tables:
SHOPPING_CART(ID, DATE)
PRODUCT(SHOPPING_CART_ID, POS, NAME, QUANTITY)
and then define class ShoppingCartPersistence:
public class ShoppingCardPersistence {
private final Connection connection;
private final ProductPersistence productPersistence;
public ShoppingCardPersistence(Connection connection) {
this.connection = connection;
this.productPersistence = new ProductPersistence(connection);
}
public void create(ShoppingCart cart) throws SQLException {
try (PreparedStatement stmt = connection.prepareStatement(
"INSERT INTO SHOPPING_CART(ID, DATE) VALUES(?, ?)")) {
stmt.setLong(1, cart.getId());
stmt.setTimestamp(2, new Timestamp(cart.getDate().getTime()));
stmt.executeUpdate();
}
productPersistence.create(cart.getId(), cart.getProducts());
}
public ShoppingCart read(long id) throws SQLException {
ShoppingCart cart;
try (PreparedStatement stmt = connection.prepareStatement(
"SELECT DATE FROM SHOPPING_CART WHERE ID=?")) {
stmt.setLong(1, id);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
return null;
}
cart = new ShoppingCart();
cart.setId(id);
cart.setDate(new Date(rs.getTimestamp(1).getTime()));
}
cart.setProducts(productPersistence.read(cart.getId()));
return cart;
}
public void update(ShoppingCart cart) throws SQLException {
productPersistence.delete(cart.getId());
try (PreparedStatement stmt = connection.prepareStatement(
"UPDATE SHOPPING_CART SET DATE=? WHERE ID=?")) {
stmt.setLong(2, cart.getId());
stmt.setTimestamp(1, new Timestamp(cart.getDate().getTime()));
stmt.executeUpdate();
}
productPersistence.create(cart.getId(), cart.getProducts());
}
public void delete(ShoppingCart cart) throws SQLException {
productPersistence.delete(cart.getId());
try (PreparedStatement stmt = connection.prepareStatement(
"DELETE SHOPPING_CART WHERE ID=?")) {
stmt.setLong(1, cart.getId());
stmt.executeUpdate();
}
}
}
and ProductPersistence:
public class ProductPersistence {
private final Connection connection;
public ProductPersistence(Connection connection) {
this.connection = connection;
}
public void create(long id, List<Product> products) throws SQLException {
if (!products.isEmpty()) {
try (PreparedStatement stmt = connection.prepareStatement(
"INSERT INTO PRODUCT(SHOPPING_CART_ID, POS, NAME, QUANTITY)"
+ " VALUES(?,?,?,?)")) {
for (int i = 0; i < products.size(); ++i) {
Product prod = products.get(i);
stmt.setLong(1, id);
stmt.setInt(2, i);
stmt.setString(3, prod.getName());
stmt.setInt(4, prod.getQuantity());
stmt.addBatch();
}
stmt.executeBatch();
}
}
}
public List<Product> read(long id) throws SQLException {
try (PreparedStatement stmt = connection.prepareStatement(
"SELECT POS, NAME, QUANTITY FROM PRODUCT"
+ " WHERE SHOPPING_CART_ID=?"
+ " ORDER BY POS")) {
List<Product> result = new ArrayList<>();
stmt.setLong(1, id);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Product prod = new Product();
prod.setQuantity(rs.getInt(2));
prod.setName(rs.getString(3));
result.add(prod);
}
return result;
}
}
public void delete(long id) throws SQLException {
try (PreparedStatement stmt = connection.prepareStatement(
"DELETE PRODUCT WHERE SHOPPING_CART_ID=?")) {
stmt.setLong(1, id);
stmt.executeUpdate();
}
}
}
You would typically use these classes with a piece of code like this:
try (Connection connection = ConnectionFactory.getConnection()) {
ShoppingCartPersistence pm
= new ShoppingCartPersistence(connection);
ShoppingCart cart = pm.read(shoppingCardId);
// do a lot of useful thing with the cart
pm.update(cart);
connection.commit();
} catch (SQLException ex) {
ex.printStackTrace();
}
Note that in your ConnectionFactory you should disable autocommit.
The ID of a shopping card has to be assigned before a call to ShoppingCardPersistence.create but databases offer mechanisms to automatically generate them, either with an autoincremented column or with a sequence.
I'm using Oracle 19c database. And HOMESQUAD_EMPLOYEE is table with columns : EMP_ID,EMP_NAME,EMP_MOBILE_NO,EMP_PASSWORD with VARCHAR2(50).
I'm trying to retrieve the row with given EMP_MOBILE_NO in Java using ResultSet object .
Connection is established successfully. PreparedStatement is getting executed successfully,ResultSet is not null but ResultSet.next() is null.
The same query is getting executed and I'm getting required row.
Here's the Code and its output.
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
//Loading Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Loading Connection
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/orcl", dbUsername, dbPassword);
//Executing query;
System.out.println("Connection Established");
//Object to store result
items = new ArrayList < Object > ();
Map properties={ActionType=ProcessLogin, mobileNo=8308856606};
queryString=buildLoginQuery(properties);
System.out.println("Query: " + queryString);
if (queryString != null && !queryString.trim().equals("")) {
System.out.println("Into P Statement If Loop");
pstmt = con.prepareStatement(queryString);
System.out.println("StateMent Prepared: " + pstmt.toString());
rs = pstmt.executeQuery();
System.out.println("Query Executed");
System.out.println("Result Set rs.next():" + rs.next()); //Error Point
while (rs != null && rs.next()) {
items.add(constructLoginProps(rs));
}
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
}
} catch (Exception e) {
System.out.println("Exception Occured in aDBExecute:" + e.getMessage());
}
//constructLoginProps Function
private HomesquadEmployee constructLoginProps(ResultSet rs) {
HomesquadEmployee vo = new HomesquadEmployee();
try {
if (rs.getString("EMP_PASSWORD") != null) {
vo.setEmpPassword(rs.getString("EMP_PASSWORD"));
}
if (rs.getString("EMP_ID") != null) {
vo.setEmpId(rs.getString("EMP_ID"));
}
if (rs.getString("EMP_NAME") != null) {
vo.setEmpName(rs.getString("EMP_NAME"));
}
if (rs.getString("EMP_MOBILE_NO") != null) {
vo.setEmpMobileNo(rs.getString("EMP_MOBILE_NO"));
}
} catch (Exception e) {
System.out.println("Exception Occured in buildLoginQuery: " + e.getMessage());
}
return (vo);
}
//HomesquadEmployee Class
public class HomesquadEmployee {
private String empId;
private String empName;
private String empMobileNo;
private String empPassword;
public HomesquadEmployee() {}
public HomesquadEmployee(String empId, String empName, String empMobileNo, String empPassword) {
this.empId = empId;
this.empName = empName;
this.empMobileNo = empMobileNo;
this.empPassword = empPassword;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpMobileNo() {
return empMobileNo;
}
public void setEmpMobileNo(String empMobileNo) {
this.empMobileNo = empMobileNo;
}
public String getEmpPassword() {
return empPassword;
}
public void setEmpPassword(String empPassword) {
this.empPassword = empPassword;
}
}
//build Query Function
private String buildLoginQuery(Map properties) throws Exception {
String mobileNo="";
String password="";
queryString="SELECT * FROM HOMESQUAD_EMPLOYEE ";
if(properties!=null && (String)properties.get("mobileNo")!=null) {
mobileNo=((String)properties.get("mobileNo")).trim();
queryString=queryString+" WHERE EMP_MOBILE_NO = "+"'"+mobileNo.toUpperCase()+"'";
}
return(queryString);
}
Output:
Connection Established.
Query: SELECT * FROM HOMESQUAD_EMPLOYEE WHERE EMP_MOBILE_NO = '8308856606'
Into P Statement If Loop
StateMent Prepared: oracle.jdbc.driver.OraclePreparedStatementWrapper#514f51cf
Query Executed
Result Set rs.next():false
Please help me out.
I'm trying to display all the data from different database table into a JTable using reflection but when i run the code I gen this kind of error:. The methods responsible for that are createViewAllQuery, ViewAll and createObjects from AbstractDAO class.
Any idea what the problem is? Thanks!
package project3;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.mysql.jdbc.PreparedStatement;
public class AbstractDAO<T>{
protected static final Logger LOGGER = Logger.getLogger(AbstractDAO.class.getName());
private final Class<T> type;
#SuppressWarnings("unchecked")
public AbstractDAO() {
this.type = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
private String createFindQuery(String field) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
sb.append(" * ");
sb.append(" FROM ");
sb.append(type.getSimpleName());
sb.append(" WHERE " + field + "=?");
return sb.toString();
}
private String createAddQuery(T object) throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
sb.append(type.getSimpleName());
sb.append(" VALUES (");
for(Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
if(field.get(object) instanceof Integer) {
sb.append(field.get(object));
sb.append(",");
}
else {
sb.append("'");
sb.append(field.get(object));
sb.append("',");
}
}
sb.deleteCharAt(sb.length()-1);
sb.append(");");
System.out.println(sb.toString());
return sb.toString();
}
private String createViewAllQuery() throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ");
sb.append(type.getSimpleName());
sb.append(";");
return sb.toString();
}
public List<T> ViewAll() throws IllegalArgumentException, IllegalAccessException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createViewAllQuery();
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
resultSet = statement.executeQuery();
return createObjects(resultSet);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
public JTable createTable(List<T> objects) throws IllegalArgumentException, IllegalAccessException {
ArrayList<String> columnNamesArrayList = new ArrayList<String>();
for(Field field : objects.get(0).getClass().getDeclaredFields()) {
field.setAccessible(true);
columnNamesArrayList.add(field.getName());
}
String[] columnNames = new String[columnNamesArrayList.size()];
columnNames = columnNamesArrayList.toArray(columnNames);
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
Iterator<T> i = objects.iterator();
while(i.hasNext()) {
T object = i.next();
ArrayList<Object> columnDataAsArrayList = new ArrayList<Object>();
for(Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
columnDataAsArrayList.add(field.get(object));
}
Object[] columnDataAsArray = new Object[columnDataAsArrayList.size()];
columnDataAsArray = columnDataAsArrayList.toArray(columnDataAsArray);
tableModel.addRow(columnDataAsArray);
}
JTable table = new JTable(tableModel);
return table;
}
public void add(T object) throws IllegalArgumentException, IllegalAccessException {
Connection connection = null;
PreparedStatement statement = null;
String query = createAddQuery(object);
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.executeUpdate();
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
}
public List<T> findByFirstName(String firstName) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createFindQuery("first_name");
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setString(1, firstName);
resultSet = statement.executeQuery();
return createObjects(resultSet);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
public T findById(int id) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createFindQuery("id");
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setInt(1, id);
resultSet = statement.executeQuery();
return createObjects(resultSet).get(0);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findById " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
private List<T> createObjects(ResultSet resultSet){
List<T> list = new ArrayList<T>();
try {
try {
while(resultSet.next()) {
T instance = type.newInstance();
for(Field field: type.getDeclaredFields()) {
Object value = resultSet.getObject(field.getName());
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
Method method = propertyDescriptor.getWriteMethod();
method.invoke(instance, value);
}
list.add(instance);
}
} catch (IllegalAccessException | SecurityException | IllegalArgumentException | InvocationTargetException | SQLException | IntrospectionException e) {
e.printStackTrace();
}
}catch(InstantiationException e) {
e.printStackTrace();
}
return list;
}
}
package project3;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.text.html.HTMLDocument.Iterator;
public class ProductsDAO extends AbstractDAO<Products>{
public ProductsDAO() {};
public static void main(String[] args) {
ProductsDAO p1 = new ProductsDAO();
//Products product1 = new Products(3, "cascaval", 5, " tip de branza facuta din lapte de vaca sau oaie", 4680);
try {
JTable table = new JTable();
table = p1.createTable(p1.ViewAll());
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
/*List<Products> list = new ArrayList<Products>();
list = p1.ViewAll();
java.util.Iterator<Products> i = list.iterator();
while(i.hasNext()) {
Products x = i.next();
System.out.println(x.getDescription());
}*/
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Here is one of the classes:
package project3;
public class Products {
private int id;
private String name;
private int price;
private String description;
private int stoc;
public Products(int id, String name, int price, String description, int stoc) {
super();
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.stoc = stoc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getStoc() {
return stoc;
}
public void setStoc(int stoc) {
this.stoc = stoc;
}
}
Your class Products hasn't got a default-constructor (so no method <init>), but you're trying to use that in
T instance = type.newInstance();
Since the Method isn't there the NoSuchMethodException is thrown.
You either have to add a default-constructor like
public Products() {
...
}
or call the constructor with arguments (probably harder to do ;)
I have a problem with my code as to where I can insert new players but I can't update them for some reason. Here is the code for my Controller and class where I keep all the methods. I am just trying to edit the camper but I am not sure as to why it's not updating them in the database at all. I can post more code if needed, just wasn't sure what was needed.
Controller:
package info.hccis.camper.web;
import info.hccis.camper.bo.CamperValidationBO;
import info.hccis.camper.dao.CamperDAO;
import info.hccis.camper.model.jpa.Camper;
import info.hccis.camper.model.jpa.User;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class CamperController {
#RequestMapping("/camper/add")
public String add(Model model, HttpSession session) {
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
Camper camper = new Camper();
model.addAttribute("camper", camper);
return "camper/add";
}
#RequestMapping("/camper/delete")
public String delete(Model model, HttpSession session, HttpServletRequest request) {
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
String id = request.getParameter("id");
CamperDAO.delete(Integer.parseInt(id));
ArrayList<Camper> campers = CamperDAO.selectAll();
model.addAttribute("campers", campers);
return "camper/list";
}
#RequestMapping("/camper/edit")
public String edit(Model model, HttpSession session, HttpServletRequest request){
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
String id = request.getParameter("id");
Camper camper = CamperDAO.select(Integer.parseInt(id));
model.addAttribute("camper", camper);
return "camper/add";
}
#RequestMapping("/camper/addSubmit")
public String addSubmit(Model model, #ModelAttribute("camper") Camper camper, HttpSession session) {
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
ArrayList<String> errors = CamperValidationBO.validateCamper(camper);
//If there is an error send them back to add page.
boolean error = false;
if (!errors.isEmpty()) {
error = true;
}
if (error) {
model.addAttribute("messages", errors);
return "/camper/add";
}
System.out.println("BJM - About to add " + camper + " to the database");
try {
CamperDAO.update(camper);
//Get the campers from the database
ArrayList<Camper> campers = CamperDAO.selectAll();
model.addAttribute("campers", campers);
} catch (Exception ex) {
System.out.println("BJM - There was an error adding camper to the database");
}
return "camper/list";
}
#RequestMapping("/camper/list")
public String showHome(Model model, HttpSession session) {
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
//Get the campers from the database
ArrayList<Camper> campers = CamperDAO.selectAll();
System.out.println("BJM-found " + campers.size() + " campers. Going to welcome page");
model.addAttribute("campers", campers);
//This will send the user to the welcome.html page.
return "camper/list";
}
}
Other Class:
package info.hccis.camper.dao;
import info.hccis.camper.dao.util.ConnectionUtils;
import info.hccis.camper.dao.util.DbUtils;
import info.hccis.camper.model.jpa.Camper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.logging.Logger;
public class CamperDAO {
private final static Logger LOGGER = Logger.getLogger(CamperDAO.class.getName());
public static synchronized void delete(int idIn) {
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
try {
conn = ConnectionUtils.getConnection();
sql = "delete FROM camper where id = ? limit 1";
ps = conn.prepareStatement(sql);
ps.setInt(1, idIn);
ps.executeUpdate();
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
}
public static Camper select(int idIn) {
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
Camper theCamper = null;
try {
conn = ConnectionUtils.getConnection();
sql = "SELECT * FROM camper WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, idIn);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
long id = rs.getInt("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String dob = rs.getString("dob");
String parentName = rs.getString("parentName");
String email = rs.getString("email");
double totalPaid = rs.getDouble("totalPaid");
theCamper = new Camper(id, firstName, lastName, parentName, email, totalPaid);
theCamper.setDob(dob);
}
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
return theCamper;
}
public static ArrayList<Camper> selectAll() {
ArrayList<Camper> campers = new ArrayList();
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
try {
conn = ConnectionUtils.getConnection();
sql = "SELECT * FROM camper order by id";
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
long id = rs.getLong("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String dob = rs.getString("dob");
String parentName = rs.getString("parentName");
String email = rs.getString("email");
double totalPaid = rs.getDouble("totalPaid");
Camper camper = new Camper(id, firstName, lastName, parentName, email, totalPaid);
camper.setDob(dob);
campers.add(camper);
}
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
return campers;
}
public static ArrayList<Camper> selectAllByDOB(String year) {
ArrayList<Camper> campers = new ArrayList();
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
try {
conn = ConnectionUtils.getConnection();
sql = "SELECT * FROM camper where dob like ? order by id";
ps = conn.prepareStatement(sql);
ps.setString(1, year+"%");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
long id = rs.getLong("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String dob = rs.getString("dob");
String parentName = rs.getString("parentName");
String email = rs.getString("email");
double totalPaid = rs.getDouble("totalPaid");
Camper camper = new Camper(id, firstName, lastName, parentName, email, totalPaid);
camper.setDob(dob);
campers.add(camper);
}
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
return campers;
}
public static synchronized Camper update(Camper camper) throws Exception {
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
/*
* Setup the sql to update or insert the row.
*/
try {
conn = ConnectionUtils.getConnection();
//Check to see if camper exists.
if (camper.getId() == null) {
sql = "SELECT max(id) from Camper";
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
long max = 0;
while (rs.next()) {
max = rs.getInt(1) + 1;
}
camper.setId(max);
sql = "INSERT INTO `Camper`(`id`, `firstName`, `lastName`, `dob`, `parentName`, `email`, `totalPaid`) "
+ "VALUES (?,?,?,?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setLong(1, camper.getId());
ps.setString(2, camper.getFirstName());
ps.setString(3, camper.getLastName());
ps.setString(4, camper.getDob());
ps.setString(5, camper.getParentName());
ps.setString(6, camper.getEmail());
ps.setDouble(7, camper.getTotalPaid());
} else {
sql = "UPDATE `camper` SET `firstName`=?,`lastName`=?,`dob`=?, `parentName`=?, `email`=?, `totalPaid`=? WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setLong(1, camper.getId());
ps.setString(2, camper.getFirstName());
ps.setString(3, camper.getLastName());
ps.setString(4, camper.getDob());
ps.setString(5, camper.getParentName());
ps.setString(6, camper.getEmail());
ps.setDouble(7, camper.getTotalPaid());
}
/*
Note executeUpdate() for update vs executeQuery for read only!!
*/
ps.executeUpdate();
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
throw e;
} finally {
DbUtils.close(ps, conn);
}
return camper;
}
}
your code for update is :
sql = "UPDATE `camper` SET `firstName`=?,`lastName`=?,`dob`=?, `parentName`=?, `email`=?, `totalPaid`=? WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setLong(1, camper.getId());
ps.setString(2, camper.getFirstName());
ps.setString(3, camper.getLastName());
ps.setString(4, camper.getDob());
ps.setString(5, camper.getParentName());
ps.setString(6, camper.getEmail());
ps.setDouble(7, camper.getTotalPaid());
You have 7 parameters and thelast is set to totalPaid valuenstead of id.
You must have:
ps.setString(1, camper.getFirstName());
ps.setString(2, camper.getLastName());
ps.setString(3, camper.getDob());
ps.setString(4, camper.getParentName());
ps.setString(5, camper.getEmail());
ps.setDouble(6, camper.getTotalPaid());
ps.setLong(7, camper.getId());
If you're using Java as your programming language and PostgreSQL as your DBMS then you could want to check the Output of any query in the console for testing purposes.
How could you print the results of any query in the console?
Just use the standard JDBC Driver for PostgreSQL in Java.
Here is a simple example of an utility class for printing any SQL Query:
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class PostgreSQLConnection {
public String host;
public String port;
public String username;
public String password;
public String database;
private Connection connection;
public PostgreSQLConnection(String host, String port, String username, String password, String database) {
super();
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.database = database;
}
public void checkDemo(String table, String pkColumn) {
try {
this.connect();
Statement stmt = null;
String query = "SELECT * FROM " + table;
stmt = this.connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("Column " + pkColumn);
while (rs.next()) {
String id = new String(rs.getBytes(pkColumn), StandardCharsets.UTF_8);
System.out.println("| Column " + id + " |");
}
this.disconnect();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
public String getResults(String sqlQuery) {
try {
String result = "";
this.connect();
Statement stmt = null;
stmt = this.connection.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
ResultSetMetaData rsMeta = rs.getMetaData();
int count = rsMeta.getColumnCount();
int i, j = 1;
result += "\n| ";
while (j <= count) {
String format = "%1$-" + rsMeta.getColumnDisplaySize(j) + "s";
String formatedValue = String.format(format, rsMeta.getColumnLabel(j));
result += formatedValue + "| ";
j++;
}
result += "\n" + new String(new char[result.length()]).replace("\0", "-");
while (rs.next()) {
i = 1;
result += "\n| ";
while (i <= count) {
String format = "%1$-" + rsMeta.getColumnDisplaySize(i) + "s";
String formatedValue = String.format(format, new String(rs.getBytes(i), StandardCharsets.UTF_8));
result += formatedValue + "| ";
i++;
}
}
this.disconnect();
return result;
} catch (Exception e) {
e.printStackTrace(System.out);
return "";
}
}
private void connect() throws Exception {
Class.forName("org.postgresql.Driver");
this.connection = null;
this.connection = DriverManager.getConnection(
"jdbc:postgresql://" + this.host + ":" + this.port + "/" + this.database, this.username, this.password);
}
private void disconnect() throws Exception {
if (this.connection != null) {
this.connection.close();
this.connection = null;
}
}
}
Here is an example of how to use it:
package com.peoplewalking.psql.demo;
public class MainDemo {
public static void main(String[] args) {
String host = "localhost";
String port = "5432";
String user = "postgres";
String pass = "postgres";
String database = "your_database_name";
PostgreSQLConnection psqlc = new PostgreSQLConnection(host, port, user, pass, database);
String prettyConsoleOutput = psqlc.getResults("SELECT Id, Name FROM Person");
System.out.println(prettyConsoleOutput);
}
}