I am not able to retrieve column values from my database table with the following coding a message has been displayed in the console:
java.sql.SQLException: Invalid value for getInt() - 'Glomindz Support'
My code is:
package com.glomindz.mercuri.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import com.glomindz.mercuri.util.MySingleTon;
public class UserServicesDAO {
private Connection connection;
public UserServicesDAO() {
// connection = new MySingleTon().getConnection();
connection = MySingleTon.getInstance().getConnection();
}
public void get_all_data() {
}
public Map<Integer, String> get_all_data1() {
HashMap<Integer, String> result = new HashMap<Integer, String>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
result.put(resultSet.getInt(1), resultSet.getString("id"));
result.put(resultSet.getInt(2), resultSet.getString("name"));
result.put(resultSet.getInt(3), resultSet.getString("email"));
result.put(resultSet.getInt(4), resultSet.getString("mobile"));
result.put(resultSet.getInt(5), resultSet.getString("password"));
result.put(resultSet.getInt(6), resultSet.getString("role"));
result.put(resultSet.getInt(7), resultSet.getString("status"));
result.put(resultSet.getInt(8),
resultSet.getString("last_update"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
new UserServicesDAO().get_all_data1();
}
}
My db table schema is:
id name email mobile password role status last_update
1 Glomindz Support support#glomindz.com 9854087006 cbf91a71c11d5ec348b0c7e9b2f0055e admin 1 2013-05-02 22:05:14
2 Amarjyoti Das amarjyotidas#splcare.com 9864092598 88f2dccb02b2a20615211e5492f85204 admin 1 2013-04-26 05:44:41
You retrieve every column as an int for the key. I assume that some of these columns represent Strings or Dates.
while(resultSet.next()){
result.put(resultSet.getInt(1),resultSet.getString("id"));
result.put(resultSet.getInt(2),resultSet.getString("name")); //Most likely a String
result.put(resultSet.getInt(3),resultSet.getString("email"));
result.put(resultSet.getInt(4),resultSet.getString("mobile"));
result.put(resultSet.getInt(5),resultSet.getString("password"));
result.put(resultSet.getInt(6),resultSet.getString("role"));
result.put(resultSet.getInt(7),resultSet.getString("status"));
result.put(resultSet.getInt(8),resultSet.getString("last_update")); //Most likely a date
}
The inconsistencies between the data types and the object/value returned by the getInt() method causes the error. I would suggest building/modeling an object in your domain that stores rows from the table. Something like:
public class User{
private Integer id;
private String name;
private String email;
private String mobile;
private String password;
private String role;
private String status;
private Date lastUpdate;
/* Get and set methods for each field */
}
Then build a Map containing the object as the value and the id as the key:
//Use Map interface here, also notice generic arguments <Integer,User>
Map<Integer, User> result = new HashMap<Integer, User>();
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while(resultSet.next()){
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name");
user.setEmail(resultSet.getString("email");
//do this for each field, using appropriate method for type...
//then add to map
result.put(user.getId(), user);
}
I think you need all your data from the table as a Map. But you may have multiple rows in your DB, therefore you basically want a list of maps! Modify your method to something like this:-
public List<Map<Integer, String>> get_all_data1() {
List<Map<Integer, String>> allRows = new ArrayList<Map<Integer, String>>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
Map<Integer, String> result = new HashMap<Integer, String>();
result.put(1, resultSet.getString("id"));
result.put(2, resultSet.getString("name"));
result.put(3, resultSet.getString("email"));
result.put(4, resultSet.getString("mobile"));
result.put(5, resultSet.getString("password"));
result.put(6, resultSet.getString("role"));
result.put(7, resultSet.getString("status"));
result.put(8, resultSet.getString("last_update"));
allRows.add(result);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return allRows;
}
Here, for every fetched record from the DB, the columns are put into the Map, and each map, represents a row, which is added to a List!
If you are using JPA annotations to map entity fields with db table, you need to use #Enumerated(EnumType.STRING) annotation on ENUM type entity fields.
This error is due to, while creating the table you may mentioned name column as INTEGER. So while retrieving it will get that column using getInt() method. But actually the column is of type STRING.
U should change the datatype of name column to STRING and this issue will be fixed automatically.
According to documentation, getInt() or getString() requires columnIndex or columnLabel to get value for that column in particular entry. To find the column index you need to use findColumn(name) method to get its columnIndex. So your code should be as follows:
while (resultSet.next()) {
result.put(resultSet.findColumn("id"), resultSet.getInt("id"));
result.put(resultSet.findColumn("name"), resultSet.getString("name"));
result.put(resultSet.findColumn("email"), resultSet.getString("email"));
result.put(resultSet.findColumn("mobile"), resultSet.getInt("mobile"));
result.put(resultSet.findColumn("password"), resultSet.getString("password"));
result.put(resultSet.findColumn("role"), resultSet.getString("role"));
result.put(resultSet.findColumn("status"), resultSet.getInt("status"));
result.put(resultSet.findColumn("last_update"),
resultSet.getString("last_update"));
}
Basically you need to get your values according to the datatype with which it had been saved in DB. Check available methods to retrieve values by Ctrl+Click on ResultSet class
Please check the syntax error for a small mistake for comma(,) you are added before the select statement
Example:
select id, name, mobile, address from table_name;
but you are using like
select id, name, mobile, address, from table_name;
please check and correct it
Related
I have a simple program that is supposed to get a user from github's API and I want to count the times the method is called.
Here is my REST Controller with a GET method (that's the method to be counted):
#RestController
#RequestMapping("/api/v1")
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
#GetMapping("/user/info/{login}")
public User getUser(#PathVariable String login) throws IOException {
userService.insertRecord(login);
return userService.fetchUser(login);
}
}
My program works (more or less) as it's supposed to, BUT .insertRecord() method does not work at all. It basically does nothing. The method SHOULD check if the database already has a user of the given login. If yes - then it should proceed to update the record and increment the REQUEST_COUNT number by 1. If no - then it should create a new record of a given login and REQUEST_COUNT as 1. The table in my database has only two column - LOGIN and REUQEST_COUNT.
But that method literally does nothing, the table in my database remains untouched.
public void insertRecord(String login) {
//this part checks if there is a login like that in the database already
String sql = "select * from calls where LOGIN = ?";
PreparedStatement preparedStatement;
ResultSet resultSet;
try {
preparedStatement = getConnection().prepareStatement(sql);
preparedStatement.setString(1, login);
resultSet = preparedStatement.executeQuery();
//if there's a result - I am trying to increment the value of REQUEST_COUNT column by 1.
if (resultSet.next()) {
String updateSql = "update calls set REQUEST_COUNT = REQUEST_COUNT + 1 where login = ?";
PreparedStatement updatePreparedStatement;
try {
updatePreparedStatement = getConnection().prepareStatement(updateSql);
updatePreparedStatement.setString(1, login);
} catch (SQLException e) {
logger.error("Could not insert a record into the database.");
e.printStackTrace();
}
//if there is no result - I want to insert a new record.
} else {
String insertSql = "insert into calls (LOGIN, REQUEST_COUNT) values (?, ?)";
try (final PreparedStatement insertPreparedStatement = getConnection().prepareStatement(insertSql)) {
insertPreparedStatement.setString(1, login);
insertPreparedStatement.setInt(2, 1);
} catch (SQLException e) {
logger.error("Could not insert a record into the database.");
e.printStackTrace();
}
}
} catch (SQLException e) {
logger.error("Operation failed.");
e.printStackTrace();
}
}
No Logger's messages are printed either, it's as if the method was simply completely ignored.
Please, help.
Because you are not calling updatePreparedStatement.executeUpdate() !
The sql will only take effetc after you call executeUpdate().
You can put a filter that will execute before/after the endpoint executed. And in that particular filter, you can also track which endpoint is executed and take appropriate action for any specific endpoint.
Can someone review my code
This query is fetching two values address_id and postcode from table1. Here
AddressID class has two variable postcode(string) and address_id(integer) :
#Select("SELECT address_id,postcode FROM table1 WHERE custom_field_1 = #{caseid}")
public List<AddressID> getAddressIdPostCodeList(String caseid);
Here is how AddressID looks AddressID.java
private int addressId;
private String postcode;
//getters and setters of Pstcode and addressId
#Override
public String toString() {
return "PostCode : " + this.postcode;
}
while executing this query I get value of address_id as 0 and required postcode. Although DB has values of address_id which is not zero. Where my code is failing?
This is where in my main method I am calling
List<AddressID> addresses = new ArrayList<>();
addresses = mainClassObject.getAddressIdPostCodeList(address.getcaseId());
Ideally addresses object should have both address_id and postcode. I am getting both values but address_id I am getting 0 and correct values for postcode.
Since I cant comment because I dont have 50 reputation, I had to write it here, its hard to tell from the code you posted, to give you an answer I need more detail on what getAddressIdPostCodeList() does, since you said the data in the DB has no ceros the error must be in the method getAddressIdPostCodeList() and/or in how you are handling the resultset of the Query
EDIT: Solution using Oracle JDBC Driver
Since I dont know how to use Mybatis, heres a solution using JDBC.
to connect using JDBC to your Oracle DB here's a simple tutorial:
1. First you need to download de JDBC driver from Oracle depending your DB version (11g,12c,10g), the driver Its called ojdbcX.jar where X is a number of the version of the driver
2. After you have downloaded the driver you need to add the .jar to your project, if you are using Netbeans IDE you can add it like this:
if you are using Eclipse you can use the following Link to see how to add the .JAR file: How to import a jar in Eclipse
3. After adding the .JAR its pretty simple, you just need to connect to the DB using your credentials, here is an example on how to do it:
Connection connection = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "system", "password"); } catch (Exception ex) {
ex.printStackTrace();
}
for more deatiled information on how to connect, you can check the oracle.jdbc
Class OracleDriver Documentation
4. After the connection has been made its pretty simple, Heres a short code example to get the result you want, you need to modify it with your connection details and as you see fit because im making a couple of assumptions, this code is just an example:
Main.Java
public class Main {
public static void main(String[] argv) {
List<AddressID> addresses;
SQLConnect conex= new SQLConnect();
String caseid="the id you want";
addresses=conex.getAddressIdPostCodeList(caseid);
}
AddressID.java
public class AddressID {
private String addressId;
private String postcode;
}
SQLConnect.Java
public class SQLConnect {
public static Connection connection;
public SQLConnect (){
createConnection();
}
public void CreateConnection(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "system", "password")
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void closeConnection(){
if(connection!=null){
try {
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public ResultSet ExecuteQuery(String queryTXT) throws SQLException{
Statement query = connection.createStatement();
ResultSet table=query.executeQuery(queryTXT);
return table;
}
public List<AddressID> getAddressIdPostCodeList(String caseid) throws SQLException{
List<AddressID> addresses = new ArrayList <> ();
ResultSet table=ExecuteQuery("SELECT address_id,postcode FROM table1 WHERE custom_field_1 ='"+caseid+"';");
while (table.next()) {
AddressID aux;
aux.addressId=table.getString(1);
aux.postcode=table.getString(2);
addresses.add(aux);
}
return addresses;
}
}
I did forgot to wtite my result query which is actually binding data fetched
from select query to the AddressId class..
#Results(id = "result",
value = {
#Result(property = "addressId", column = "address_id"),
#Result(property = "postcode", column = "postcode")
}
)
I am trying to implement code which will have resultset using simpljdbccall or jdbccall or namedtemplatejdbc
Code will use my stored procedure which is database proc having input parameter and an REF cursor.
I did not found any code which will help me to extract cursor as output to have all multiple rows details in in my resultset using JDBC
DATABASE PROCEDURE
BOOKING_PG.get_infant_info_pr(
c_booking_id IN T_BOOKED_INFANT_INFO.BOOKING_ID%TYPE,
c_booked_infant_details OUT booked_infant_details
)
OPEN c_booked_infant_details FOR
SELECT
BOOKING_ID c_booking_id,
BOOKED_INFANT_INFO_ID c_booked_infant_info_id,
BOOKED_ADULT_PAX_INFO_ID c_booked_adult_pax_info_id,
FROM T_BOOKED_INFANT_INFO T
WHERE T.BOOKING_ID = c_booking_id
and T.STATUS_ID = 1;
JAVA Code
SimpleJdbcCall call = new SimpleJdbcCall(dataSource2)
.withCatalogName("BOOKING_PG")
.withProcedureName("get_infant_info_pr")
.withoutProcedureColumnMetaDataAccess()
.returningResultSet("rs1", new ParameterizedRowMapper() {
#Override
public Object[] mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Object[]{rowNum, rs.getLong("c_booking_id"), rs.getLong(c_booked_infant_info_id) , rs.getLong(c_booked_adult_pax_info_id)};
}
});
SqlParameterSource in = new MapSqlParameterSource()
.addValue(C_BOOKING_ID, bookingId);
Map<String, Object> res = call.execute(in);
List<Object[]> l1 = (List<Object[]>)res.get("rs1");
It is throwing SQL error
org.springframework.jdbc.BadSqlGrammarException: CallableStatementCallback; bad SQL grammar [{call EURONOVA.BOOKING_PG.GET_INFANT_INFO_PR(?)}]; nested exception is java.sql.SQLException: ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'GET_INFANT_INFO_PR'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
I am not sure if there is something wrong in the code or we have to follow some different way to get resultset in simplejdbc call
Can someone please help me in this topic?
First create a class having similar data type and names which your cursor returns.
In your case create a class named BookedInfantDetails.java
public class BookedInfantDetails{
private int bookingId;
private int bookedInfantinfoId;
private int bookedadultpaxinfoid;
public int getBookingId() {
return bookingId;
}
public void setBookingId(int bookingId) {
this.bookingId = bookingId;
}
public int getBookedInfantinfoId() {
return bookedInfantinfoId;
}
public void setBookedInfantinfoId(int bookedInfantinfoId) {
this.bookedInfantinfoId = bookedInfantinfoId;
}
public int getBookedadultpaxinfoid() {
return bookedadultpaxinfoid;
}
public void setBookedadultpaxinfoid(int bookedadultpaxinfoid) {
this.bookedadultpaxinfoid = bookedadultpaxinfoid;
}
}
Now declare in and out parameters in the jdbccall and map the ref cursor to the class using beanproperty rowmapper.
SimpleJdbcCall call = new SimpleJdbcCall(dataSource2)
.withCatalogName("BOOKING_PG")
.withProcedureName("get_infant_info_pr")
.withoutProcedureColumnMetaDataAccess()
.declareParameters(new SqlParameter("c_booking_id", OracleTypes.Integer),
new SqlParameter("c_booked_infant_details", OracleTypes.CURSOR),
.returningResultSet("c_booked_infant_details",
BeanPropertyRowMapper.newInstance(BookedInfantDetails.class));
SqlParameterSource in = new MapSqlParameterSource()
.addValue(C_BOOKING_ID, bookingId);
Map<String, Object> res = call.execute(in);
List<BookedInfantDetails> l1=
(List<BookedInfantDetails>)res.get("c_booked_infant_details");
Find Our more details on spring docs....
https://docs.spring.io/spring-data/jdbc/old-docs/1.2.1.RELEASE/reference/html/orcl.datatypes.html#orcl.datatypes.ref_cur
I have a webapp where I need to retrieve data from DB via JDBC and display it front end. Its a static data and it wont be changed. So I just need the data to be retrieved just once and store in a static variable and so I can use that data every time instead of querying the database. Below is the sample code:
public class SampleClass(){
static Map<String, BigDecimal> productMap = null;
public Map<String, BigDecimal> getDatafromDB(Connection conn, PreparedStatement stmt, ResultSet rs) throws SQLException{
if(productMap == null){
productMap = getProductID(conn, stmt, rs);
}
return productMap;
}
public Map<String, BigDecimal> getProductID(Connection conn, PreparedStatement stmt, ResultSet rs) throws SQLException {
logger.debug("retrieving product ID's from product table..");
Map<String, BigDecimal> productMap = new HashMap<String, BigDecimal>();
stmt = conn.prepareStatement("Select * from PRODUCTTABLE");
rs = stmt.executeQuery();
logger.debug("Product ID's retrieved");
while(rs.next()){
productMap.put(rs.getString("PRODUCT_NAME"),rs.getBigDecimal("PRODUCT_ID"));
}
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
return productMap;
}
}
I am calling this method from UI through a http servlet request. For the first time when I run it, since the map is null it queries the data base and gets the data and sends it to UI. When I hit the servlet again for the second time with the new request the product map is null and again its querying the database and getting the data. Since its a static variable it should be only initialized once rite so why is it still null for the second request. Can someone please correct my code ?
Thanks in advance
The root cause of your problem is that a servlet is memoryless. So a static variable will not help. What you need is a session attribute instead.
I suggest adding your variable as a session attribute. In the first place you need to create an encapsulating class that implements Serializable:
public class SampleResult implements Serializable {
private Map<String, String> productMap;
public void setProductMap(Map<String, String> productMap) {
this.productMap = productMap;
}
public Map<String, String> getProductMap() {
return productMap;
}
}
Now in your servlet:
HttpSesssion session = request.getSession();
Map<String, String> productMap;
SampleResult result;
if (session.getAttribute("productMap") == null) {
productMap = retrievedatafromDB();
result = new SampleResult();
sampleResult.setProductMap(productMap);
session.setAttribute("productMap", result);// session attribute created
} else {
result = session.getAttribute("productMap");// retrieve session attribute
productMap = result.getProductMap();
}
I have an aplication which create a number of query (update or insert) and then each query is executed.
The whole code is working fine but I've saw that my server IO latency is too much during this proccess.
The code execute a loop which is taking arround 1 minute.
Then what I wanted to do is write each query in memory instead to execute it, and then, once I have the whole list of query to execute, use "LOAD DATA LOCAL INFILE" from mysql, which will take less time.
My question is: How can I write all my query (String object) in a "File" or "any other container" in java to use it after the loop?.
#user3283548 This is my example code:
Class1:
import java.util.ArrayList;
public class Class1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ArrayList<String> Staff=new ArrayList<String>();
Staff.add("tom");
Staff.add("Laura");
Staff.add("Patricia");
for (int x = 0; x < Staff.size(); x++) {
System.out.println(Staff.get(x));
Class2 user = new Class2 (Staff.get(x));
user.checkUser();
}
}
}
Class2:
public class Class2 {
private String user;
public Class2(String user){
this.user=user;
}
public void checkUser() throws Exception{
if (user.equals("tom")){
String queryUser="update UsersT set userStatus='2' where UserName='"+user+"';";
Class3 updateUser = new Class3(queryUser);
updateUser.UpdateQuery();;
}else{
String queryUser="Insert into UsersT (UserName,userStatus)Values('"+user+"','1');";
Class3 updateUser = new Class3(queryUser);
updateUser.InsertQuery();
System.out.println(user+" is not ton doing new insert");
}
}
}
Class3:
public class Class3 {
public String Query;
public Class3(String Query){
this.Query = Query;
}
public void UpdateQuery() throws Exception{
/*// Accessing Driver From Jar File
Class.forName("com.mysql.jdbc.Driver");
//DB Connection
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/default","root","1234567");
String sql =Query;
PreparedStatement pst = con.prepareStatement(sql);*/
System.out.println(Query); //Just to test
//pst.execute();
}
public void InsertQuery() throws Exception{
/*// Accessing Driver From Jar File
Class.forName("com.mysql.jdbc.Driver");
//DB Connection
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/default","root","1234567");
String sql =Query;
PreparedStatement pst = con.prepareStatement(sql);*/
System.out.println(Query); //Just to test
//pst.execute();
}
}
Then, what I wanted to do is create an ArraList in Class1 and use it in Class3 to collect all the queries which has to be executed.
The idea is to execute the list of queries in one time, once the main process is finished, istead to do it for each element within in loop of the Class1. I wanted to do it, because I think it will be take less resource IO from the server HD
Your loop is probably too slow because you're building up Strings using String
I'd hazard a guess you're doing things like
String query = "SELECT * FROM " + variablea + " WHERE + variableb + " = " ...
If you're doing a lot of string concatenation then use StringBuilder as every time you change a string it is actually re-created which is expensive. Simply changing your code to use StringBuilder instead of string will probably cut your loop executed time to a couple of MS. Simply call .toString() method of StringBuilder obj to get the string.
Storing objects
If you want to store anything for later use you should store it in a Collection. If you want a a key-value relationship then use a Map (HashMap would suit you fine). If you just want the values use an List (ArrayList is most popular).
So for example if I wanted to store query strings for later use I would...
Construct the string using StringBuilder.
Put the string (by calling .toString() into a HashMap
Get the query string from the HashMap...
You should never store things on disk if you don't need them to be persistent over application restarts and even then I'd store them in a database not in a file.
Hope this helps.
Thanks
David
EDIT: UPDATE BASED ON YOU POSTING YOUR CODE:
OK this needs some major re-factoring!
I've kept it really simple because I don't have a lot of time to re-write comprehensively.
I've commented where I have made corrections.
Your major issue here is creating objects in loops. You should just create the object once as creating objects is expensive.
I've also corrected other coding issues and replaced the for loop as you shouldn't be writing it like that.I've also renamed the classes to something useful.
I've not tested this so you may need to do some work to get it to work. But this should be a lot faster.
OLD CLASS 1
import java.util.ArrayList;
import java.util.List;
public class StaffChecker {
public static void main(String[] args) throws Exception {
// Creating objects is expensive, you should do this as little as possible
StaffCheckBO staffCheckBO = new StaffCheckBO();
// variables should be Camel Cased and describe what they hold
// Never start with ArrayList start with List you should specific the interface on the left side.
List<String> staffList = new ArrayList<String>();
staffList.add("tom");
staffList.add("Laura");
staffList.add("Patricia");
// use a foreach loop not a (int x = 0 ... ) This is the preffered method.
for (String staffMember : staffList) {
// You now dont need to use .get() you can access the current variable using staffMember
System.out.println(staffMember);
// Do the work
staffCheckBO.checkUser(staffMember);
}
}
}
OLD CLASS 2
/**
* Probably not really any need for this class but I'll assume further business logic may follow.
*/
public class StaffCheckBO {
// Again only create our DAO once...CREATING OBJECTS IS EXPENSIVE.
private StaffDAO staffDAO = new StaffDAO();
public void checkUser(String staffMember) throws Exception{
boolean staffExists = staffDAO.checkStaffExists(staffMember);
if(staffExists) {
System.out.println(staffMember +" is not in database, doing new insert.");
staffDAO.insertStaff(staffMember);
} else {
System.out.println(staffMember +" has been found in the database, updating user.");
staffDAO.updateStaff(staffMember);
}
}
}
OLD CLASS 3
import java.sql.*;
/**
* You will need to do some work to get this class to work fully and this is obviously basic but its to give you an idea.
*/
public class StaffDAO {
public boolean checkStaffExists(String staffName) {
boolean staffExists = false;
try {
String query = "SELECT * FROM STAFF_TABLE WHERE STAFF_NAME = ?";
PreparedStatement preparedStatement = getDBConnection().prepareStatement(query);
// Load your variables into the string in order to be safe against injection attacks.
preparedStatement.setString(1, staffName);
ResultSet resultSet = preparedStatement.executeQuery();
// If a record has been found the staff member is in the database. This obviously doesn't account for multiple staff members
if(resultSet.next()) {
staffExists = true;
}
} catch (SQLException e) {
System.out.println("SQL Exception in getStaff: " + e.getMessage());
}
return staffExists;
}
// Method names should be camel cased
public void updateStaff(String staffName) throws Exception {
try {
String query = "YOUR QUERY";
PreparedStatement preparedStatement = getDBConnection().prepareStatement(query);
// Load your variables into the string in order to be safe against injection attacks.
preparedStatement.setString(1, staffName);
ResultSet resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
System.out.println("SQL Exception in getStaff: " + e.getMessage());
}
}
public void insertStaff(String staffName) throws Exception {
try {
String query = "YOUR QUERY";
PreparedStatement preparedStatement = getDBConnection().prepareStatement(query);
// Load your variables into the string in order to be safe against injection attacks.
preparedStatement.setString(1, staffName);
ResultSet resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
System.out.println("SQL Exception in getStaff: " + e.getMessage());
}
}
/**
* You need to abstract the connection logic away so you avoid code reuse.
*
* #return
*/
private Connection getDBConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/default", "root", "1234567");
} catch (ClassNotFoundException e) {
System.out.println("Could not find class. DB Connection could not be created: " + e.getMessage());
} catch (SQLException e) {
System.out.println("SQL Exception. " + e.getMessage());
}
return connection;
}
}