Database not updating with thymeleaf and JDBC - java

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());

Related

How to Composition/Association/List of Objects in DAO implementation

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.

ResultSet.next() is false. Even though table is not empty

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.

WebApplication made using Struts keeps inserting null values to the database

I'm working on a sample user-based java web application. When I try to add a user via registration to my database. After capturing the data on the front end, the records get stored as null values
i.e a row of my users table would contain the values (7, null, null, null, null) (using template id(primary-key), f_name, l_name, email, password).
Below are the files I believe could cause possible problems
User.java
package com.ysg.data;
import com.ysg.service.PasswordEncrypter;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
public class User implements Serializable {
private String id;
private String password;
private String firstName;
private String lastName;
private String email;
public User(){
// default
}
public User( String password, boolean isEncrypted, String firstName, String
lastName, String email){
this.password = isEncrypted ? password : encrypt(password);
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
} //getters and setters follow
UserRepository.java
package com.ysg.repository;
import com.ysg.data.User;
import com.ysg.exception.DuplicateItemException;
import com.ysg.exception.RepositoryException;
import com.ysg.util.MySQLHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UserRepository implements RepositoryInt<User> {
private static final String INSERT = "INSERT INTO ysg.users (f_name, l_name, email, password) values (?, ?, ?, ?)";
private static final String USER_LOGIN = "SELECT * FROM ysg.users WHERE email=? and password=?";
private static final String USER_FETCH = "SELECT * FROM ysg.users WHERE email='";
private static final String FIRSTNAME = "f_name";
private static final String LASTNAME = "l_name";
private static final String EMAIL= "email";
private static final String PASSWORD = "password";
public UserRepository(){
// default
}
#Override
public User login(User obj){
User result = find(obj);
if (result != null) {
return result;
}
return null;
}
#Override
public User register(User obj){
if (obj != null && (find(obj) == null)) {
return add(obj);
}
return null;
}
private User add(User user){
Connection conn = null;
try {
conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(INSERT);
stmt.setString(1, user.getFirstName());
stmt.setString(2, user.getLastName());
stmt.setString(3, user.getEmail());
stmt.setString(4, user.getPassword());
stmt.execute();
closeStatement(stmt);
return user;
}
catch (SQLException ex) {
if (ex.getMessage().contains("Duplicate")) {
System.out.println("Item with duplicate id already exists in repository");
throw new DuplicateItemException("Item with duplicate id already exists in repository");
}
else {
ex.printStackTrace();
System.out.println("Failed to add item to repository");
throw new RepositoryException(ex);
}
}
finally {
closeConnection(conn);
}
}
private User fetch(User user){
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute(USER_FETCH + user.getEmail()+ "'");
ResultSet resultSet = stmt.getResultSet();
User result = marshall(resultSet);
closeStatement(stmt);
return result;
}
catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Failed to fetch item from repository");
throw new RepositoryException(ex);
}
finally {
closeConnection(conn);
}
}
private User find(User user){
Connection conn = null;
try {
conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(USER_LOGIN);
stmt.setString(1, user.getEmail());
stmt.setString(2, user.getPassword());
ResultSet resultSet = stmt.executeQuery();
User result = marshall(resultSet);
closeStatement(stmt);
return result;
}
catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Failed to add item to repository");
throw new RepositoryException(ex);
}
finally {
closeConnection(conn);
}
}
private User marshall(ResultSet result) throws RepositoryException, SQLException{
if (result == null) {
return null;
}
User user = null;
if (result.next()) {
// String id = result.getString(ID);
String password = result.getString(PASSWORD);
String firstName = result.getString(FIRSTNAME);
String lastName = result.getString(LASTNAME);
String email = result.getString(EMAIL);
user = new User(password, true, firstName, lastName, email);
}
return user;
}
private Connection getConnection(){
return MySQLHelper.getConnection();
}
private static void closeStatement(Statement stmt){
if (stmt != null) {
try {
stmt.close();
//stmt = null;
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
private void closeConnection(Connection conn){
if (conn != null) {
try {
conn.close();
conn = null;
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
MySQLHelper.java
package com.ysg.util;
import com.ysg.data.User;
import com.ysg.exception.DuplicateItemException;
import com.ysg.exception.RepositoryException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class MySQLHelper {
private static final String INSERT_USER = "INSERT INTO users(f_name, l_name, email, password) values (?, ?, ?, ?)";
private static final String USER_FETCH = "SELECT * FROM users WHERE id='";
private static final String FETCH_ALL = "SELECT * FROM users";
private static final String COUNT_ALL_USERS = "SELECT COUNT(*) FROM users";
private static final String DELETE_ALL = "DELETE FROM users";
private static final String ID = "id";
private static final String EMAIL = "email";
private static final String PASSWORD = "password";
private static final String FIRSTNAME = "f_name";
private static final String LASTNAME = "l_name";
private static final String DS_NAME = "jdbc/sen301DS";
private static Context envCtx;
private static DataSource ds;
static {
try {
Context ctx = new InitialContext();
envCtx = (Context) ctx.lookup("java:/comp/env");
System.out.println(envCtx);
}
catch (Exception ex) {
System.out.println("ConnectionPool will not be available - only direct connection can be used");
}
}
public static List<User> fetch() throws SQLException{
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute(FETCH_ALL);
ResultSet resultSet = stmt.getResultSet();
List<User> result = marshall(resultSet);
closeStatement(stmt);
return result;
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeConnection(conn);
}
}
public static User fetch(String id) throws SQLException{
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute(USER_FETCH + id + "'");
ResultSet resultSet = stmt.getResultSet();
List<User> result = marshall(resultSet);
closeStatement(stmt);
return result.get(0);
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeConnection(conn);
}
}
public static User add(User user){
Connection conn = null;
try {
conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(INSERT_USER);
stmt.setString(1, user.getFirstName());
stmt.setString(2, user.getLastName());
stmt.setString(3, user.getEmail());
stmt.setString(4, user.getPassword());
stmt.execute();
closeStatement(stmt);
return user;
}
catch (SQLException ex) {
if (ex.getMessage().contains("Duplicate")) {
System.out.println("Item with duplicate id already exists in repository");
throw new DuplicateItemException("Item with duplicate id already exists in repository");
}
else {
ex.printStackTrace();
System.out.println("Failed to add item to repository");
throw new RepositoryException(ex);
}
}
finally {
closeConnection(conn);
}
}
public static int countusers() throws SQLException{
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute(COUNT_ALL_USERS);
ResultSet resultSet = stmt.getResultSet();
int count = 0;
if (resultSet.next()) {
count = resultSet.getInt(1);
}
closeStatement(stmt);
return count;
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeConnection(conn);
}
}
public static void reset() throws SQLException{
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate(DELETE_ALL);
closeStatement(stmt);
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeConnection(conn);
}
}
private static List<User> marshall(ResultSet result) throws SQLException{
List<User> list = new ArrayList<User>();
if (result == null) {
return list;
}
while (result.next()) {
String firstName = result.getString(FIRSTNAME);
String lastName = result.getString(LASTNAME);
String email = result.getString(EMAIL);
String passwd = result.getString(PASSWORD);
User user = new User(passwd, true, firstName, lastName, email);
list.add(user);
}
return list;
}
private static DataSource getDataSource(){
DataSource ds = null;
try {
ds = (DataSource) envCtx.lookup(DS_NAME);
}
catch (NamingException ex) {
ex.printStackTrace();
throw new RepositoryException("Failed to get DataSource");
}
return ds;
}
public static Connection getConnection(){
Connection con = null;
try {
con = getDataSource().getConnection();
}
catch (SQLException ex) {
ex.printStackTrace();
throw new RepositoryException("Failed to get connection to database server");
}
catch (Exception ex) {
con = getDirectConnection();
}
return con;
}
private static Connection getDirectConnection(){
try {
String conURL = "jdbc:mysql://localhost:3306/ysg?serverTimezone=UTC&useSSL=false&" + "user=sen301&password=sen301";
return DriverManager.getConnection(conURL);
}
catch (SQLException ex) {
ex.printStackTrace();
throw new RepositoryException("Failed to get direct connection to database server");
}
catch (Exception ex) {
ex.printStackTrace();
throw new RepositoryException(ex);
}
}
private static void closeStatement(Statement stmt){
if (stmt != null) {
try {
stmt.close();
stmt = null;
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
private static void closeConnection(Connection conn){
if (conn != null) {
try {
conn.close();
conn = null;
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}

How to print any PostgreSQL query result in the console using Java?

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);
}
}

java.lang.NullPointerException on MVC structured program [closed]

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

Categories