How to print any PostgreSQL query result in the console using Java? - 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);
}
}

Related

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.

SOAP WEB SERVICE - javax.xml.ws.WebServiceException: class com.developer.jaxws.Update do not have a property of the name devdesc

I am wondering why I am getting this error in my soap web server. where could I insert the property needed to properly deploy it. I have tried creating new web service and recreate the operations but the same error persist. I also tried removing and reinstalling glassfish server. where could I find it? I am using Netbeans 8.0.2 with glassfish 4.0. Thanks
javax.xml.ws.WebServiceException: class com.developer.jaxws.Update do not have a property of the name devdesc
at com.sun.xml.ws.server.sei.EndpointArgumentsBuilder$DocLit.<init>(EndpointArgumentsBuilder.java:610)
at com.sun.xml.ws.server.sei.TieHandler.createArgumentsBuilder(TieHandler.java:143)
at com.sun.xml.ws.server.sei.TieHandler.<init>(TieHandler.java:115)
at com.sun.xml.ws.db.DatabindingImpl.<init>(DatabindingImpl.java:110)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:74)
at com.sun.xml.ws.db.DatabindingProviderImpl.create(DatabindingProviderImpl.java:58)
at com.sun.xml.ws.db.DatabindingFactoryImpl.createRuntime(DatabindingFactoryImpl.java:127)
at com.sun.xml.ws.server.EndpointFactory.createSEIModel(EndpointFactory.java:487)
at com.sun.xml.ws.server.EndpointFactory.create(EndpointFactory.java:283)
at com.sun.xml.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:158)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:577)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:560)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:639)
at org.glassfish.webservices.WSServletContextListener.registerEndpoint(WSServletContextListener.java:267)
at org.glassfish.webservices.WSServletContextListener.contextInitialized(WSServletContextListener.java:104)
at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:5362)
at com.sun.enterprise.web.WebModule.contextListenerStart(WebModule.java:743)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5898)
source code
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.developer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
/**
*
* #author PCTechRinz
*/
#WebService(serviceName = "ProjectSoapService")
public class ProjectSoapService {
Connection con = DBConnect.serverConnect();
private String uniquename;
private String desc;
private int id;
public void setUniqueName(String value){ this.uniquename = value;}
public void setDescription(String value){ this.desc = value;}
public void setID(int value){ this.id = value;}
public String getUniqueName(){ return this.uniquename;}
public String getDescription() {return this.desc;}
public int getID(){ return this.id; }
/**
* Web service operation
*/
#WebMethod(operationName = "insert")
public String insert(#WebParam(name = "name") String name, #WebParam(name = "id") int id, #WebParam(name = "devdesc") String description) {
String res = "";
try {
String sq = "Insert into projects(uniquename,id,descrption) values ('"
+ name + "','"
+ id + "','"
+ description + "');";
PreparedStatement st = con.prepareStatement(sq);
st.execute();
res = "Success";
} catch (Exception e) {
res = e.toString();
}
return res;
}
/**
* Web service operation
*/
#WebMethod(operationName = "search")
public String search(#WebParam(name = "name") String name) {
String res = "";
this.id = 0;
this.uniquename = "";
this.desc = "";
try {
String query = "SELECT * FROM projects where uniquename='" + name + "';";
// create the java statement
Statement st = con.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next()) {
this.id = Integer.valueOf(rs.getString("id"));
this.uniquename = rs.getString("uniquename");
this.desc = rs.getString("description");
}
st.close();
res = "Found";
} catch (SQLException e) {
res = e.toString();
}
return res;
}
/**
* Web service operation
*/
#WebMethod(operationName = "delete")
public String delete(#WebParam(name = "name") String name) {
String res = "";
try {
String sq = "Delete from projects where uniquename ='" + name + "';";
PreparedStatement st = con.prepareStatement(sq);
st.execute();
res = "Success";
} catch (Exception e) {
res = e.toString();
}
return res;
}
/**
* Web service operation
*/
#WebMethod(operationName = "update")
public String update(#WebParam(name = "name") String name, #WebParam(name = "id") int id, #WebParam(name = "devdesc") String description) {
String res = "";
String found = this.search(uniquename);
if (found.equals("Found")) {
try {
String query = "update projects set id = '"
+ String.valueOf(id) + "', description = '"
+ description + "' where uniquename = '"
+ name + "'";
PreparedStatement preparedStmt = con.prepareStatement(query);
// execute the java preparedstatement
preparedStmt.executeUpdate();
res = "Success";
} catch (SQLException e) {
res = e.toString();
}
} else {
res = "Not Exist";
}
return res;
}
}
changing property name does not work

Java MySQL null resultset

I'm trying to write a small java application that returns the details for an employee. Here's my Employee class.
public class Employees {
private int id;
private Date dateofBirth;
private String firstName;
private String lastName;
private enum gender{
M, F;
}
private gender employeeGender;
private Date dateHired;
public String getEmployeeGender() {
return this.employeeGender.name();
}
public void setEmployeeGender(String employeeGender) {
this.employeeGender = gender.valueOf(employeeGender);
}
/*Getters, setters omitted*/
Here's my DAO class
public class EmployeeDao {
final String TABLE_EMPLOYEES = "employees";
final String COLUMN_EMPLOYEES_ID = "emp_no";
final String COLUMN_EMPLOYEES_DOB = "birth_date";
final String COLUMN_EMPLOYEES_FIRST_NAME = "first_name";
final String COLUMN_EMPLOYEES_LAST_NAME = "last_name";
final String COLUMN_EMPLOYEES_GENDER = "gender";
final String COLUMN_EMPLOYEES_HIRE_DATE = "hire_date";
final String QUERY_EMPLOYEES = "SELECT * FROM " + TABLE_EMPLOYEES + " WHERE " + COLUMN_EMPLOYEES_ID + " = ?";
public Employees getEmployeeDetails(int employeeId) {
Employees employee = new Employees();
try (DbConnection dbConnection = new DbConnection();
Connection databaseConnection = dbConnection.getConn();
PreparedStatement selectFromEmployees = databaseConnection.prepareStatement(QUERY_EMPLOYEES)) {
selectFromEmployees.setInt(1, employeeId);
try (ResultSet result = selectFromEmployees.executeQuery()) {
if (result.next() == false) {
System.out.println("Empty Resultset");
}
while (result.next()) {
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return employee;
}
}
But when I try to run the app in main method like this, I get an output with null values.
public static void main(String[] args) {
EmployeeDao employeeDao = new EmployeeDao();
Employees employees = employeeDao.getEmployeeDetails(39256);
System.out.println(employees.getId() + " \n" + employees.getFirstName() + " \n" + employees.getLastName() + " \n" + employees.getDateofBirth() + " \n" + employees.getDateHired());
}
This is the output.
This is how the corresponding row looks like in the database
You should not call next twice, since it will move the cursor forward again. Try this:
if (result.next() == false) {
System.out.println("Empty Resultset");
} else {
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
Calling ResultSet#next moves the cursor forward a row, so your if condition loses the first row. Since you know your query can return at most one row, you don't need the while loop at all, however:
public Employees getEmployeeDetails(int employeeId) throws SQLException {
Employees employee = null;
try (DbConnection dbConnection = new DbConnection();
Connection databaseConnection = dbConnection.getConn();
PreparedStatement selectFromEmployees =
databaseConnection.prepareStatement(QUERY_EMPLOYEES)) {
selectFromEmployees.setInt(1, employeeId);
try (ResultSet result = selectFromEmployees.executeQuery()) {
if (result.next()) {
employee = new Employees();
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
}
}
return employee;
}
No need to add extra result.next() comparison.
if (result.next() == false) {
System.out.println("Empty Resultset");
}
while (result.next()){
}
while will execute only if there are any rows.
Check the size of list generated before using to check if it contains value or not.

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

Iterating through an array populated from a MySQL table

There's a fair bit of code involved and I'm not sure how much detail to go into, but I'm populating a treemap with data from a mysql table and I'm having trouble iterating through it.
Here's the code for the class containing the treemap
public class SeasonResults{
private static Map<String,SeasonResults> allResults = new TreeMap<String,SeasonResults>();
private String hometeam;
private String awayteam;
private String result;
private static SeasonResults result6;
public static SeasonResults add(String hometeam, String awayteam, String result)
{
result6 = new SeasonResults(hometeam, awayteam, result);
allResults.put(hometeam,result6);
return result6;
}
private SeasonResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;
}
public static Collection<SeasonResults> getCollection()
{
return allResults.values();
}
#Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}
And here's the code where I populate the array and then try and iterate through it.
public void HeadToHead(){
try
{
//Sets up the connedtion to the database and installs drivers which are required.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");
String SQL = "SELECT * FROM PreviousSeasons WHERE HomeTeam=? and AwayTeam=?";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
prepst.setString(2,box2.getSelectedItem().toString());
rs = prepst.executeQuery();
while (rs.next())
{
//This retrieves each row of League table and adds it to an array in the League Results class.
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
custs = (hometeam + "," + awayteam + "," + result); // Takes all the variables containging a single customers information and puts it into a string, seperated by commas.
SeasonResults.add(hometeam, awayteam, result);
}
}
catch (Exception e)
{
System.out.println("Error " +e);
}
Seasonrecord = SeasonResults.getCollection();
seasons = new SeasonResults[Seasonrecord.size()];
Iterator iterateSeason = Seasonrecord.iterator();
int i = 0;
while(iterateSeason.hasNext()){
seasons[i] = (SeasonResults)iterateSeason.next();
i++;
if(result.equals("HW")){
hometeamvalue = hometeamvalue + 50;
}
else if(result.equals("D")){
hometeamvalue = hometeamvalue + 10;
awayteamvalue = awayteamvalue + 10;
}
else{
if(result.equals("AW")){
awayteamvalue = awayteamvalue + 50;
}
}
}
}
There are 5 'result' fields in the database. 2 are 'HW', 2 are 'AW', and 1 is 'D'. What I'm trying to do is print out 'hometeamvalue' and 'awayteamvalue' but when I do the value is printed as only 10. Only the first field's value is used.
I use the same code to iterate through the array when I want to display the results in a GUI, and all the fields are shown. But when I try and do some calculations with them, it doesn't work.
Any ideas what the problem is?
You have to do like this
SeasonResults.java
public class SeasonResults{
private String hometeam;
private String awayteam;
private String result;
public String getHometeam() {
return hometeam;
}
public void setHometeam(String hometeam) {
this.hometeam = hometeam;
}
public String getAwayteam() {
return awayteam;
}
public void setAwayteam(String awayteam) {
this.awayteam = awayteam;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public SeasonResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;
}
#Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}
HeadToHaed method
public void HeadToHead(){
String hometeam,awayteam,result;
int hometeamvalue,awayteamvalue;
List<SeasonResults> allResults = new ArrayList<SeasonResults>();
try
{
//Sets up the connedtion to the database and installs drivers which are required.
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");
String SQL = "SELECT * FROM PreviousSeasons WHERE HomeTeam=? and AwayTeam=?";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
prepst.setString(2,box2.getSelectedItem().toString());
ResultSet rs = prepst.executeQuery();
SeasonResults seasonResults=null;
while (rs.next())
{
//This retrieves each row of League table and adds it to an array in the League Results class.
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
seasonResults=new SeasonResults( hometeam, awayteam, result) ;
custs = (hometeam + "," + awayteam + "," + result); // Takes all the variables containging a single customers information and puts it into a string, seperated by commas.
allResults.add(seasonResults);
}
}
catch (Exception e)
{
System.out.println("Error " +e);
}
System.out.println("SIze of ArrayList::"+allResults.size());
for(SeasonResults temp:allResults)
{
if(temp.getResult().equals("HW")){
hometeamvalue = hometeamvalue + 50;
}
else if(temp.getResult().equals("D")){
hometeamvalue = hometeamvalue + 10;
awayteamvalue = awayteamvalue + 10;
}
else{
if(temp.getResult().equals("AW")){
awayteamvalue = awayteamvalue + 50;
}
}
}
}
Let Me Know If U Face Any Issues

Categories