Incrementing values in jdbc - java

I have a class called DatabaseInterface where I have my tables created over there with get Customer as a method which is as follows:
public static Customer getCustomer(long id) {
System.out.println("Get customer " + id);
Customer customer = new Customer();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM customer where id = " + id);
if (resultSet.next())
{
long cId = resultSet.getLong("id");
String name = resultSet.getString("name");
long tagNo = resultSet.getLong("tagNo");
String email = resultSet.getString("EMAIL");
String telephoneNo = resultSet.getString("telephoneNo");
int noOfTimesRecycled = resultSet.getInt("No of Times Recycled");
customer = buildCustomer(cId, name, tagNo, telephoneNo, email, noOfTimesRecycled);
System.out.println(customer);
}
} catch (SQLException ex) {
System.out.println("Error in getting customer");
ex.printStackTrace();
}
return customer;
}
I have a text file that reads value of the tagNo and each time there's a new entry for a tag it increments the value of noOfTimesRecycled.
Am doing that in a new class called UpdateTag. So I called the method getCustomer from DatabaseInterface class first and then will move on with the updates but getting error.
package com.qmul.rfid.service;
import java.util.List;
import com.qmul.rfid.dataaccess.DatabaseInterface;
//import com.qmul.rfid.dom.Customer;
import com.qmul.rfid.reader.ImportTagJob;
public class UpdateTag {
List<String> fileList = ImportTagJob.fetchData();
{
try{
for (String tag : fileList)
{
DatabaseInterface.getCustomer(long id); //Getting error on long id -Syntax error on token "long", delete this token
System.out.println(tag);
}
}
catch (IllegalArgumentException ex)
{
ex.printStackTrace();
}
}
}
Any idea why?

Related

How can I perform a get request to my Database with a REST API in Java having the Requestparameters "columnName" and "columnValue"?

I'm trying to perform a get request to my PostgreSQL Database which is supposed to work as an adaptable Search. For this request I have the parameters "columName" and "value".
My Java Code is the following:
#GetMapping("/product/search")
#ResponseStatus(HttpStatus.OK)
public ProductList searchProduct(#RequestParam(name = "fieldName") String fieldName,
#RequestParam(name = "value") String value
){
ProductList productList = new ProductList();
productList.searchProduct(fieldName, value);
return productList;
}
and
public void searchProduct(String fieldName, String value){
ProductManager productManager = PostgresProductManagerImpl.getPostgresProductManagerImpl();
productManager.searchProduct(fieldName, value);
}
and
public Collection<Product> searchProduct(String fieldName, String value) {
List<Product> products = new ArrayList<>();
Statement stmt = null;
Connection connection = null;
try {
connection = basicDataSource.getConnection();
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM products p WHERE p."+fieldName+" = " + value);
while (rs.next()){
products.add(
new Product(
rs.getString("name"),
rs.getString("description"),
rs.getString("location"),
rs.getString("alcoholContent"),
rs.getInt("likes"),
rs.getInt("dislikes"),
rs.getInt("productID")
)
);
}
}catch (SQLException e) {
e.printStackTrace();
}
try {
stmt.close();
connection.close();
}catch (SQLException e){
e.printStackTrace();
}
return products;
}
I tried some stuff out by now but nothing really made it work.
In my RestClient I request a get method with
/api/v1.0/product/search?fieldName=namet&value=beer
I hope that I described my problem well enough for some help.

Problem with implementing sql queries into Javafx

I wanted to ask a question about implementing SQL queries into a JavaFX application, specifically, I've been trying to create an "employee" application that connects to a MySQL database hosted in localhost. I'm using a DAO pattern to do this and the code is apparently right, the only problem I'm having is that I keep getting errors when trying to add a new employee to the table. Specifically, I'm getting an SQL syntax error and I have no idea what is wrong with the code.
I'll put the code for my EmployeeDAO class down there, please ignore the SQL errors in all the methods (I haven't corrected it yet), the method I already corrected and is still giving me problems is the insertEmp() method.
package Model;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import Util.DBUtil;
import java.sql.*;
public class EmployeeDAO {
//Select an Employee
public static Employee searchEmployee (String empId) throws SQLException, ClassNotFoundException{
String selectStmt = "SELECT * FROM employees WHERE employeeId="+empId;
try{
ResultSet rsEmp = DBUtil.dbExecuteQuery(selectStmt);
Employee employee = getEmployeeFromResultSet(rsEmp);
return employee;
}catch (SQLException e){
System.out.println("While Searching An Employee With "+empId+" Id, An Error Occurred");
e.printStackTrace();
throw e;
}
}
private static Employee getEmployeeFromResultSet(ResultSet rs) throws SQLException{
Employee emp = null;
if(rs.next()){
emp = new Employee();
emp.setEmployeeId(rs.getInt("EMPLOYEE_ID"));
emp.setFirstName(rs.getString("FIRST_NAME"));
emp.setLastName(rs.getString("LAST_NAME"));
emp.setEmail(rs.getString("EMAIL"));
emp.setPhoneNumber(rs.getString("PHONE_NUMBER"));
emp.setHireDate(rs.getDate("HIRE_DATE"));
emp.setJobId(rs.getString("JOB_ID"));
emp.setSalary(rs.getInt("SALARY"));
emp.setCommissionPct(rs.getDouble("COMMISSION_PCT"));
emp.setManagerId(rs.getInt("MANAGER_ID"));
emp.setDepartmentId(rs.getInt("DEPARTMENT_ID"));
}
return emp;
}
//Select Employees
public static ObservableList<Employee> searchEmployees() throws SQLException,ClassNotFoundException{
String selectStmt="SELECT * FROM employees";
try{
ResultSet rsEmps = DBUtil.dbExecuteQuery(selectStmt);
ObservableList<Employee> empList = getEmployeeList(rsEmps);
return empList;
}catch(SQLException e){
System.out.println("SQL Select Operation Failed");
e.printStackTrace();
throw e;
}
}
//Select * from employees operation
private static ObservableList<Employee> getEmployeeList(ResultSet rs) throws SQLException,ClassNotFoundException{
ObservableList<Employee> empList = FXCollections.observableArrayList();
while(rs.next()){
Employee emp = new Employee();
emp.setEmployeeId(rs.getInt("EMPLOYEE_ID"));
emp.setFirstName(rs.getString("FIRST_NAME"));
emp.setLastName(rs.getString("LAST_NAME"));
emp.setEmail(rs.getString("EMAIL"));
emp.setPhoneNumber(rs.getString("PHONE_NUMBER"));
emp.setHireDate(rs.getDate("HIRE_DATE"));
emp.setJobId(rs.getString("JOB_ID"));
emp.setSalary(rs.getInt("SALARY"));
emp.setCommissionPct(rs.getDouble("COMMISSION_PCT"));
emp.setManagerId(rs.getInt("MANAGER_ID"));
emp.setDepartmentId(rs.getInt("DEPARTMENT_ID"));
empList.add(emp);
}
return empList;
}
//Update an employee's email address
public static void updateEmpEmail(String empId, String empEmail) throws SQLException, ClassNotFoundException{
String updateStmt = "BEGIN\n" +
" UPDATE employees\n" +
" SET EMAIL = '" + empEmail + "'\n" +
" WHERE EMPLOYEE_ID = " + empId + ";\n" +
" COMMIT;\n" +
"END;";
try{
DBUtil.dbExecuteQuery(updateStmt);
}catch(SQLException e){
System.out.println("An Error Occurred While Updating The Information");
e.printStackTrace();
throw e;
}
}
public static void deleteEmpWithId(String empId) throws SQLException, ClassNotFoundException{
String updateStmt = "BEGIN\n" +
" DELETE FROM employees\n" +
" WHERE employee_id ="+ empId +";\n" +
" COMMIT;\n" +
"END;";
try{
DBUtil.dbExecuteQuery(updateStmt);
}catch(SQLException e){
System.out.println("An Error Occurred While Deleting An Employee With Id: "+empId);
e.printStackTrace();
throw e;
}
}
public static void insertEmp(String name, String lastName, String email) throws SQLException, ClassNotFoundException{
String updateStmt = "BEGIN\n" +
" INSERT INTO employees ('FIRST_NAME', 'LAST_NAME', 'EMAIL', 'HIRE_DATE', 'JOB_ID')\n" +
" VALUES\n" +
" (?, ?, ?, SYSDATE, 'IT_PROG');\n" +
" END;";
try{
DBUtil.dbPreparedStatement(updateStmt, name, lastName, email);
}catch(SQLException e){
System.out.println("An Error Occurred While Adding A New Employee To The Table");
e.printStackTrace();
throw e;
}
}
}
I'll also add down here the code that uses the insertEmp method.
public static void dbPreparedStatement(String sqlStmt, String name, String lastName, String email) throws SQLException,ClassNotFoundException{
PreparedStatement stmt = null;
try{
dbConnect();
stmt=conn.prepareStatement(sqlStmt);
stmt.setString(1, name);
stmt.setString(2, lastName);
stmt.setString(3, email);
stmt.execute();
}catch(SQLException e){
System.out.println("Error Occured At ExecutePreparedStatement Operation");
e.printStackTrace();
throw e;
}
dbDisconnect();
}
As shree mentioned, I made a mistake when writing down column names, I fixed that, also fixed an error regarding the SYSDATE() function being written mistakingly as only SYSDATE. The SQL still wouldn't work, so I took out the BEGIN and END lines and it works fine now, no idea why though.

Exception in thread "http-apr-8080-exec-11"

My java application was running fine, but now only some functionality of it throws this error
Exception in thread "http-apr-8080-exec-11" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2367)
at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:587)
at java.lang.StringBuilder.append(StringBuilder.java:214)
at org.apache.struts2.json.JSONWriter.add(JSONWriter.java:575)
functionalities are add campaign and delete campaign. When i try to add a campaign or delete a campaign this error is thrown.
Theres option of adding keywords in each campaign, that is running fine. and also other parts of application is running fine.
code snippet of the delete campaign service
public String deleteSerpsCampaign() {
objRequest = ServletActionContext.getRequest();
//initializing http session object
objSession = objRequest.getSession();
//checking for 'customerID' attribute in session
if (objSession.getAttribute("customerID") != null) {
Integer campaignId = 0;
campaignId = Integer.parseInt(jString);
System.out.println("Site id is:::" + campaignId);
//reading the 'customerID' from session and type casting it to integer
Integer customerID = (Integer) objSession.getAttribute("customerID");
//now invoking the deleteCampaign() method of CampaignsServiceImpl
String campaignName = objCampaignsService.deleteCampaign(campaignId, customerID);
message = "'" + campaignName + "' - Campaign has been Deleted";
objSession.setAttribute("message", message);
return SUCCESS;
}
//if session attribute 'customerID' is null then return result parameter as 'LOGIN'
//this result parameter is mapped in 'struts.xml'
return LOGIN;
}
deleteCampaign method
public String deleteCampaign(Integer campaignId, Integer customerID) {
int delCount = 0;
Campaigns objcamp = (Campaigns) getSession().get(Campaigns.class, campaignId);
try {
Collection objserpkeywords = objcamp.getSerpkeywordsCollection();
Iterator itr = objserpkeywords.iterator();
while (itr.hasNext()) {
Serpkeywords objserpkeys = (Serpkeywords) itr.next();
if (objserpkeys.getVisibility() == 1) {
delCount++;
objserpkeys.setVisibility(0);
getSession().update(objserpkeys);
}
}
Collection objseokeywords = objcamp.getSeokeyworddetailsCollection();
Iterator ittr = objseokeywords.iterator();
while (ittr.hasNext()) {
Seokeyworddetails objseokeys = (Seokeyworddetails) itr.next();
if (objseokeys.getVisibility() == 1) {
objseokeys.setVisibility(0);
getSession().update(objseokeys);
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
String sQuery = "update campaigns set visibility=0 where CampaignID=:campaignId";
SQLQuery objQuery = getSession().createSQLQuery(sQuery);
objQuery.setParameter("campaignId", campaignId);
objQuery.executeUpdate();
} catch (DataAccessResourceFailureException | IllegalStateException | HibernateException ex) {
l.error(ex + " " + ex.getMessage());
}
Customers objCustomers = (Customers) getSession().get(Customers.class, customerID);
try {
objCustomers.setActiveSerpCampaignsCount(objCustomers.getActiveSerpCampaignsCount() - 1);
objCustomers.setActiveKeywordCount(objCustomers.getActiveKeywordCount() - delCount);
getSession().update(objCustomers);
} catch (DataAccessResourceFailureException | IllegalStateException | HibernateException ex) {
l.error(ex + " " + ex.getMessage());
}
return objcamp.getCampaign();
}

Display Records From MySQL Database using JTable in Java

I want to connect a JTable to a ResultSet from a MySQL database so I can view the data.
I am looking for some links or code snippets describing this task. I'm using the Netbeans IDE..
Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable in Java.
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFromMySqlDatabase extends JFrame
{
public TableFromMySqlDatabase()
{
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/yourdb";
String userid = "root";
String password = "sesame";
String sql = "SELECT * FROM animals";
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:
Otherwise the code will throw an SQLException stating that the driver cannot be found.
Now in my example, yourdb is the name of the database and animals is the name of the table that I am performing a query against.
Here is what will be output:
Parting note:
You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.
ArrayList
Vector
Try-with-resources statement
this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project
and do that :
1- creat a connection
2- statment and resultset
3- creat a jtable
4- give the result set to DbUtils.resultSetToTableModel(rs)
as define in this methode you well get your jtable so easy.
public void afficherAll(String tableName){
String sql="select * from "+tableName;
try {
stmt=con.createStatement();
rs=stmt.executeQuery(sql);
tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, e);
}
}
If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:
First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.
package financialdocuments;
import java.lang.*;
import java.util.HashMap;
/**
*
* #author Administrator
*/
public class Document {
private int document_number;
private boolean document_type;
private boolean document_status;
private StringBuilder document_date;
private StringBuilder document_statement;
private int document_code_number;
private int document_employee_number;
private int document_client_number;
private String document_employee_name;
private String document_client_name;
private long document_amount;
private long document_payment_amount;
HashMap<Integer,Activity> document_activity_hashmap;
public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){
document_date = new StringBuilder(dd);
document_date.setLength(10);
document_date.setCharAt(4, '.');
document_date.setCharAt(7, '.');
document_statement = new StringBuilder(dst);
document_statement.setLength(50);
document_number = dn;
document_type = dt;
document_status = ds;
document_code_number = dcon;
document_employee_number = den;
document_client_number = dcln;
document_amount = da;
document_employee_name = dena;
document_client_name = dcna;
document_payment_amount = 0;
document_activity_hashmap = new HashMap<>();
}
public Document(int dn,boolean dt,boolean ds, long dpa){
document_number = dn;
document_type = dt;
document_status = ds;
document_payment_amount = dpa;
document_activity_hashmap = new HashMap<>();
}
// Print document information
public void printDocumentInformation (){
System.out.println("Document Number:" + document_number);
System.out.println("Document Date:" + document_date);
System.out.println("Document Type:" + document_type);
System.out.println("Document Status:" + document_status);
System.out.println("Document Statement:" + document_statement);
System.out.println("Document Code Number:" + document_code_number);
System.out.println("Document Client Number:" + document_client_number);
System.out.println("Document Employee Number:" + document_employee_number);
System.out.println("Document Amount:" + document_amount);
System.out.println("Document Payment Amount:" + document_payment_amount);
System.out.println("Document Employee Name:" + document_employee_name);
System.out.println("Document Client Name:" + document_client_name);
}
}
Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.
package financialdocuments;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Administrator
*/
public class DataBase {
/**
*
* Defining parameters and strings that are going to be used
*
*/
//Connection connect;
// Tables which their datas are extracted at the beginning
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;
// Resultset Returned by queries
private ResultSet result;
// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
public DataBase(){
code_table = new HashMap<>();
activity_table = new HashMap<>();
client_table = new HashMap<>();
employee_table = new HashMap<>();
Initialize();
}
/**
* Set variables and objects for this class.
*/
private void Initialize(){
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Get tables' information
selectCodeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printCodeTableQueryArray();
selectActivityTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printActivityTableQueryArray();
selectClientTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printClientTableQueryArray();
selectEmployeeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printEmployeeTableQueryArray();
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
/**
* Write Queries
* #param s
* #return
*/
public boolean insertQuery(String s){
boolean ret = false;
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Set tables' information
try {
Statement st = connect.createStatement();
int val = st.executeUpdate(s);
if(val==1){
System.out.print("Successfully inserted value");
ret = true;
}
else{
System.out.print("Unsuccessful insertion");
ret = false;
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
return ret;
}
/**
* Query needed to get code table's data
* #param c
* #return
*/
private void selectCodeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM code;");
while (res.next()) {
int id = res.getInt("code_number");
String msg = res.getString("code_statement");
code_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printCodeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* #param c
* #return
*/
private void selectActivityTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM activity;");
while (res.next()) {
int id = res.getInt("activity_number");
String msg = res.getString("activity_statement");
activity_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printActivityTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get client table's data
* #param c
* #return
*/
private void selectClientTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM client;");
while (res.next()) {
int id = res.getInt("client_number");
String msg = res.getString("client_full_name");
client_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printClientTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* #param c
* #return
*/
private void selectEmployeeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee;");
while (res.next()) {
int id = res.getInt("employee_number");
String msg = res.getString("employee_full_name");
employee_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printEmployeeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
}
I hope this could be a little help.

Junit test case for database insert method with DAO and web service

I am implementing a webservice based university management system. This system adds certain courses to database. here below is the code that I am using.
Course.java
public class Course {
private String courseName;
private String location;
private String courseId;
public String getCourseId()
{
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
then another file is as below
CourseDaoImpl.java
public class CourseDaoImpl implements IDao {
Connection conn = null;
Statement stmt = null;
public CourseDaoImpl(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/univesitydb", "root", "root");
stmt = conn.createStatement();
if (!conn.isClosed())
System.out.println("Successfully connectiod");
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
#Override
public String add(Object object) {
Course c = (Course) object ;
String courseId = c.getCourseId();
String courseName = c.getCourseName();
String location = c.getLocation();
String result = "";
int rowcount;
try {
String query = "Insert into course (courseId,courseName,location) values"
+ " ('"
+ courseId
+ "', '"
+ courseName
+ "', '"
+ location
+ "')";
rowcount = stmt.executeUpdate(query);
if (rowcount > 0) {
result = "true";
System.out.println("Course inserted successful");
} else {
result = "false:The data could not be inserted in the databse";
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
the third is the Web service file as follows which interacts with the previous two and adds data to database.
CourseService.java
package edu.service;
import edu.dao.IDao;
import edu.dao.impl.CourseDaoImpl;
import edu.db.entity.Course;
public class CourseService {
public String addCourse(String courseId, String courseName, String location)
{
Course c = new Course();
c.setCourseId(courseId);
c.setCourseName(courseName);
c.setLocation(location);
IDao dao = new CourseDaoImpl();
return dao.add(c);
}
Looking at my code listings can any body suggest me how do I write test case for my add method. I am totally beginner for JAVA, I took help from my friends to learn this java part and Now need to implement Junit test for my database methods like add course above.
Please suggest some thing that I can learn , read and use to implement Junit testing for my database methods.
This is one sample dao test using junit in spring project.
import java.util.List;
import junit.framework.Assert;
import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
#Transactional
#TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
#Autowired
private MemberDao memberDao;
#Test
public void testFindById()
{
Member member = memberDao.findById(0l);
Assert.assertEquals("John Smith", member.getName());
Assert.assertEquals("john.smith#mailinator.com", member.getEmail());
Assert.assertEquals("2125551212", member.getPhoneNumber());
return;
}
#Test
public void testFindByEmail()
{
Member member = memberDao.findByEmail("john.smith#mailinator.com");
Assert.assertEquals("John Smith", member.getName());
Assert.assertEquals("john.smith#mailinator.com", member.getEmail());
Assert.assertEquals("2125551212", member.getPhoneNumber());
return;
}
#Test
public void testRegister()
{
Member member = new Member();
member.setEmail("jane.doe#mailinator.com");
member.setName("Jane Doe");
member.setPhoneNumber("2125552121");
memberDao.register(member);
Long id = member.getId();
Assert.assertNotNull(id);
Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
Member newMember = memberDao.findById(id);
Assert.assertEquals("Jane Doe", newMember.getName());
Assert.assertEquals("jane.doe#mailinator.com", newMember.getEmail());
Assert.assertEquals("2125552121", newMember.getPhoneNumber());
return;
}
#Test
public void testFindAllOrderedByName()
{
Member member = new Member();
member.setEmail("jane.doe#mailinator.com");
member.setName("Jane Doe");
member.setPhoneNumber("2125552121");
memberDao.register(member);
List<Member> members = memberDao.findAllOrderedByName();
Assert.assertEquals(2, members.size());
Member newMember = members.get(0);
Assert.assertEquals("Jane Doe", newMember.getName());
Assert.assertEquals("jane.doe#mailinator.com", newMember.getEmail());
Assert.assertEquals("2125552121", newMember.getPhoneNumber());
return;
}
}
The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.
To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.
A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.
As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.
#Test
public void testSearchManagementStaff() throws SQLException
{
boolean res=true;
ManagementDaoImp mdi=new ManagementDaoImp();
boolean b=mdi.searchManagementStaff("abc#gmail.com"," 123456");
assertEquals(res,b);
}
/*
public class UserDAO {
public boolean insertUser(UserBean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into regis values(?,?,?,?,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getname());
statement.setString(2, u.getlname());
statement.setString(3, u.getemail());
statement.setString(4, u.getusername());
statement.setString(5, u.getpasswords());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
} finally {
return flag;
}
}
public String userValidate(UserBean u) {
String login = "";
MySqlConnection msq = new MySqlConnection();
try {
String email = u.getemail();
String Pass = u.getpasswords();
String sql = "SELECT name FROM regis WHERE email=? and passwords=?";
com.mysql.jdbc.Connection connection = msq.getConnection();
com.mysql.jdbc.PreparedStatement statement = null;
ResultSet rs = null;
statement = (com.mysql.jdbc.PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, email);
statement.setString(2, Pass);
rs = statement.executeQuery();
if (rs.next()) {
login = rs.getString("name");
} else {
login = "false";
}
} catch (Exception e) {
} finally {
return login;
}
}
public boolean getmessage(UserBean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into feedback values(?,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getemail());
statement.setString(2, u.getfeedback());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
} finally {
return flag;
}
}
public boolean insertOrder(cartbean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into cart (product_id, email, Tprice, quantity) values (?,?,2000,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getpid());
statement.setString(2, u.getemail());
statement.setString(3, u.getquantity());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
System.out.print("hi");
} finally {
return flag;
}
}
}

Categories