how do i use select statment - mysql

I want to use select max from a table. I want to use a PreparedStatement. I have a composite primary key which consists of the t.v series and the epo number. When I add new epo it will for table and bring the t.v series code from guidline table the content of all the programs and the code for each and then add to the new table. I want it to get the last epo by getting the max and then increment +1 "an automation app".
So how can I select max where id =??
If you get me its like
pstm2=con.prepareStatement(max);
String max="select MAX(epono) as eponoo from archieve wwhere id like ? ";

This program would be helpful
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SelectRecordsUsingPreparedStatement {
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:databaseName";
String username = "name";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select deptno, deptname, deptloc from dept where deptno > ?";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setInt(1, 1001); // set input parameter
rs = pstmt.executeQuery();
// extract data from the ResultSet
while (rs.next()) {
int dbDeptNumber = rs.getInt(1);
String dbDeptName = rs.getString(2);
String dbDeptLocation = rs.getString(3);
System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Related

How do I work with aws rds myql on eclipse(Java)?

I have downloaded aws sdk and connected my account and the database. But now I do not know what I need to do next. How do insert, delete or create table through java on eclipse.
I know to do these in a local database. I tried changing the url in getConnection() function to the my endpoint on eclipse but I keep getting error stating
"Access denied for user 'aws'#'xxx.xxx.xxx.xxx' (using password: YES)" (real IP modified for security reasons).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private static final String url = "jdbc:mysql://aws.cyduxshnlizb.ap-south-1.rds.amazonaws.com:3306";
final private String user = "myusername";
final private String passwd = "mypassword";
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection(url,user,passwd);
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from feedback.comments");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into feedback.comments values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from feedback.comments");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from feedback.comments");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from feedback.comments where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from feedback.comments");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}

Want to update MySQL DB with the values from excel sheet in minimal time

I have written below code to read cells from excel and then update it to MySQL table. There are more than 2000 records and this code is only updating the last record but not all the records. If I put 'pstm.executeBatch();' inside for loop, then it updates all the records but one by one, which takes about 2 minutes. I want to reduce this time, so added "&rewriteBatchedStatements=true" in URL and put 'pstm.executeBatch();' outside for loop. In console it shows reading of all the records but the database has only the last record updated.
package com.company.testdata;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UpdateDataCopy {
public static void main(String[] args) throws Exception {
String user = "root";
String pass = "test";
String jdbcUrl = "jdbc:mysql://192.1.2.1/db_bro_mumbai?useSSL=false"+
"&rewriteBatchedStatements=true";
String driver = "com.mysql.jdbc.Driver";
try {
PreparedStatement pstm = null;
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
FileInputStream input = new FileInputStream("E:\\Work\\TestData.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (XSSFRow) sheet.getRow(i);
int id = (int)row.getCell(0).getNumericCellValue();
System.out.println(id);
String firstname = row.getCell(2).getStringCellValue();
System.out.println(firstname);
String middlename = row.getCell(3).getStringCellValue();
System.out.println(middlename);
String lastname = row.getCell(4).getStringCellValue();
System.out.println(lastname);
int physicalFitness = (int)row.getCell(25).getNumericCellValue();
System.out.println(physicalFitness);
String sql = "UPDATE fitness_details as p SET p.physicalFitness = ? "
+ " WHERE CandidateID_FK1 = ?";
pstm = (PreparedStatement) myConn.prepareStatement(sql);
pstm.setInt(1, physicalFitness);
pstm.setInt(2, id);
pstm.addBatch();
//Adding below line will update record one by one which is time consuming, so I commented this and added it after for loop.
//pstm.executeBatch();
System.out.println("Import rows " + i);
}
pstm.executeBatch();
System.out.println("Imported");
//myConn.commit();
//pstm.close();
//myConn.close();
input.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
Has mentioned in my comment...
package com.company.testdata;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UpdateDataCopy {
public static void main(String[] args) throws Exception {
String user = "root";
String pass = "test";
String jdbcUrl = "jdbc:mysql://172.16.206.197/db_bro_mumbai?useSSL=false"+
"&rewriteBatchedStatements=true";
String driver = "com.mysql.jdbc.Driver";
try {
PreparedStatement pstm = null;
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
String sql = "UPDATE fitness_details as p SET p.physicalFitness = ? WHERE CandidateID_FK1 = ?";
pstm = myConn.prepareStatement(sql);
FileInputStream input = new FileInputStream("E:\\Work\\TestData.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (XSSFRow) sheet.getRow(i);
int id = (int)row.getCell(0).getNumericCellValue();
String firstname = row.getCell(2).getStringCellValue();
String middlename = row.getCell(3).getStringCellValue();
String lastname = row.getCell(4).getStringCellValue();
int physicalFitness = (int)row.getCell(25).getNumericCellValue();
pstm.setInt(1, physicalFitness);
pstm.setInt(2, id);
pstm.addBatch();
System.out.println("Import rows " + I + "ID: " + id + " Middlename:" + middlename + " Lastname:" + lastname + " Physicalfitness:" + physicalFitness );
}
pstm.executeBatch();
System.out.println("Imported");
//myConn.commit();
pstm.close();
myConn.close();
input.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
I got the solution. The reason for time delay was due to 'AutoCommit' set to 'true' by default. So I set 'myConn.setAutoCommit(false);' before loop and then run the code. It took about 8 seconds to update db for 2000 records which was about 2 minutes earlier. Below is the code for reference -
package com.company.testdata;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UpdateDataCopy {
public static void main(String[] args) throws Exception {
String user = "root";
String pass = "test";
String jdbcUrl = "jdbc:mysql://192.1.2.1/db_bro_mumbai?useSSL=false";
String driver = "com.mysql.jdbc.Driver";
try {
PreparedStatement pstm = null;
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
FileInputStream input = new FileInputStream("E:\\Work\\TestData.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
myConn.setAutoCommit(false);
/*final int batchSize = 1000;
int count = 0;*/
long start = System.currentTimeMillis();
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (XSSFRow) sheet.getRow(i);
int id = (int)row.getCell(0).getNumericCellValue();
System.out.println(id);
String firstname = row.getCell(2).getStringCellValue();
System.out.println(firstname);
String middlename = row.getCell(3).getStringCellValue();
System.out.println(middlename);
String lastname = row.getCell(4).getStringCellValue();
System.out.println(lastname);
int physicalFitness = (int)row.getCell(25).getNumericCellValue();
System.out.println(physicalFitness);
String sql = "UPDATE fitness_details as p SET p.physicalFitness = ? "
+ " WHERE CandidateID_FK1 = ?";
pstm = (PreparedStatement) myConn.prepareStatement(sql);
pstm.setInt(1, physicalFitness);
pstm.setInt(2, id);
pstm.addBatch();
pstm.executeBatch();
System.out.println("Import rows " + i);
}
System.out.println("Time Taken="+(System.currentTimeMillis()-start));
myConn.commit();
myConn.setAutoCommit(true);
pstm.close();
myConn.close();
input.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}

Query MySQL DB using preparedStatement.setDate

public java.util.List<Tag> getAlltagsByDate(String date ){
DataSource dataSource = new DataSource();
Connection conn = dataSource.createConnection();
ResultSet resultSet = null;
PreparedStatement stmt = null;
Tag tags_Data = new Tag();
String query = "select * from tag_data where tag_data_date = ?";
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date nn =df.parse(date);
stmt = conn.prepareStatement(query);
stmt.setDate(1, java.sql.Date.valueOf(date));
resultSet = stmt.executeQuery(query);
I am getting an error
Can anyone help me with this,
I need to query mySQL db where date = input in html
No, skip the Date part; simply use the string. Let's see the value of (String date ).
MySQL is happy if you can end up with ... tag_data_date = '2015-12-11'.
If String date looks like '2015-12-11', then the conversion to Date is unnecessary.
I have presented a solution. As you have not mentioned much about your DB structure, so ,
Consider test as database name, and consisting of table tag_data having two columns id and tag_data_date as shown below.
CREATE TABLE `tag_data` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`tag_data_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Also consider data in table as
INSERT INTO `tag_data` (`id`, `tag_data_date`) VALUES
(1, '2015-12-20 00:00:00');
And your java class as below
public class JDBCPreparedStatementExample {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver"; //mysql driver class
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/test"; //connectionstring
private static final String DB_USER = "root"; //mysql username
private static final String DB_PASSWORD = "root"; //mysql password
public static void main(String[] argv) throws ParseException {
try {
getDateForDate("2015-12-20"); //time passed as arguement
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
//Method to interact with DB and print data,this can be changed to return value of List<Key> as per your requirement
private static void getDateForDate(String date) throws SQLException, ParseException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date dateCal =df.parse(date); // parse date in String to Date Object
String updateTableSQL = "select * from tag_data where tag_data_date = ?";
try {
//get DB connection
dbConnection = getDBConnection();
// Create preapared statement
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setDate(1, new Date(dateCal.getTime()));//convert java.util.Date to java.sql.Date
// execute update SQL stetement
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getString(2);
int id = resultSet.getInt("id");
Date tag_data_date = resultSet.getDate("tag_data_date");
System.out.println("Date: " + tag_data_date);
System.out.println("Comment: " + id);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}

JavaServlet handling SQL errors

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
{
PrintWriter out=res.getWriter();
res.setContentType("text/html");
Connection conn = null;
final String id = UUID.randomUUID().toString();
Map m = req.getParameterMap();
Set s = m.entrySet();
Iterator it = s.iterator();
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "username", "password");
String sqlStr = "insert into transactions (LogID,KeyName,KeyValue) "
+ "values (?,?,?)";
while(it.hasNext()){
Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>)it.next();
String key = entry.getKey();
String[] value = entry.getValue();
try (PreparedStatement stmt = conn.prepareStatement(sqlStr)) {
stmt.setString(1, id);
stmt.setString(2, key);
stmt.setString(3, value[0].toString());
out.println("<html><head><title>Callback Script</title></head><body>");
out.println("<h3>Inserted into the database:</h3>");
out.println("<p>Parameter: " + key + " and Value = " + value[0].toString() + "</p>");
int updateCount = stmt.executeUpdate();
for (Enumeration<String> en = req.getParameterNames(); en.hasMoreElements();) {
String paramName = en.nextElement();
String paramValue = req.getParameter(paramName);
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
out.close();
try {
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
If some error happens with the MySQL Database like wrong credentials, any SQL syntax error at all should be handled and displayed but it is not displaying at all.
Any advice on this or am I coding it wrong?
Cheers
What you have will only print to the logs. To print to the page, use out.print
catch (SQLException ex)
{
ex.printStackTrace(); //print to log
out.print("<br/>Error: " + ex.getMessage()); //print to page
}
On credentials errors you won't want to print the actual message to the page, as it might include the credentials. So you should isolate the part the opens the connection with its own try-catch, which can be nested inside this one.
try
{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "username", "password");
}
catch(Exception ex_connError)
{
out.print("<br/>Error making db connection");
}

Constructor must be called super error in JSP, JDBC, servlet and forms

I'm creating a registration form for my web application and I'm getting the following error when I try to access register a new user:
java.lang.VerifyError: (class: eBooks/Data/UserDB, method: <init> signature: ()V) Constructor must call super() or this() java.lang.VerifyError: (class: eBooks/Data/UserDB, method: <init> signature: ()V) Constructor must call super() or this()
at eBooks.controller.RegisterUserServlet.doPost(RegisterUserServlet.java:62)
This is the UserDB class:
package eBooks.Data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import eBooks.business.User;
import eBooks.util.DBUtil;
public class UserDB {
public static int insert(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query =
"INSERT INTO User (fName, lName, email_address, password, dataOfBirth, phone,"
+ " address, city, state, country, zipcode, accountType)"
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getfName());
ps.setString(2, user.getlName());
ps.setString(3, user.getEmailAddress());
ps.setString(4, user.getPassword());
ps.setString(5, user.getDateOfBirth());
ps.setString(5, user.getPhone());
ps.setString(6, user.getAddress());
ps.setString(7, user.getCity());
ps.setString(8, user.getCountry());
ps.setString(9, user.getState());
ps.setString(10, user.getZipcode());
//ps.setString(11, user.getAccountType()); -- Ask Jassin
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static int update(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE User SET"
+ "fName = ?"
+ "lName = ?"
+ "password = ?"
+ "dateOfBirth = ?"
+ "phone = ?"
+ "address = ?"
+ "city = ?"
+ "state_or_Region = ?"
+ "country = ?"
+ "zip = ?"
+ ""
+ "WHERE email_address= ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getfName());
ps.setString(2, user.getlName());
ps.setString(3, user.getEmailAddress());
ps.setString(4, user.getPassword());
ps.setString(5, user.getDateOfBirth());
ps.setString(5, user.getPhone());
ps.setString(6, user.getAddress());
ps.setString(7, user.getCity());
ps.setString(8, user.getCountry());
ps.setString(9, user.getState());
ps.setString(10, user.getZipcode());
//ps.setString(11, user.getAccountType()); -- Ask Jassin
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static int delete(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "DELETE FROM User" +
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getEmailAddress());
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static boolean emailExists(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT email_address FROM User"+
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
return rs.next();
}
catch(SQLException e)
{
e.printStackTrace();
return false;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static User selectUser(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM User"+
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
User user = null;
if (rs.next())
{
user = new User();
user.setfName(rs.getString("fName"));
user.setlName(rs.getString("lName"));
user.setEmailAddress(rs.getString("emailAddress"));
user.setPassword(rs.getString("password"));
user.setPhone(rs.getString("phone"));
user.setDateOfBirth(rs.getString("dateOfBirth"));
user.setAddress(rs.getString("address"));
user.setCity(rs.getString("city"));
user.setCountry(rs.getString("country"));
user.setState(rs.getString("state"));
user.setZipcode(rs.getString("zip"));
// user.setAccountType(rs.getString("accountType")); -- Ask Jassin
}
return user;
}
catch(SQLException e)
{
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
This is the RegisterUserServlet:
package eBooks.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import eBooks.business.User;
import eBooks.business.Account;
import eBooks.Data.UserDB;
public class RegisterUserServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession();
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String emailAddress = request.getParameter("emailAddress");
String password = request.getParameter("password");
String dateOfBirth = request.getParameter("dateOfBirth");
String phone = request.getParameter("phohe");
String address = request.getParameter("address");
String city = request.getParameter("city");
String country = request.getParameter("country");
String state = request.getParameter("country");
String accountType = request.getParameter("accountType");
//TO DO: Account acctTypeList = request.getParameter("acctTypeList"); add this an object first
User user = new User();
user.setfName(fName);
user.setlName(lName);
user.setEmailAddress(emailAddress);
user.setPassword(password);
user.setDateOfBirth(dateOfBirth);
user.setAddress(address);
user.setCity(city);
user.setCountry(country);
user.setState(state);
user.setZipcode(phone);
//TODO: user.setAccountType(accTypeList); -- Ask Jassin
// Add information to the database
if(UserDB.emailExists(emailAddress))
UserDB.update(user);
else
UserDB.update(user);
session.setAttribute("User", user);
Cookie emailCookie = new Cookie("emailCookie", emailAddress);
emailCookie.setMaxAge(60*60*24*365*2);
emailCookie.setPath("/");
response.addCookie(emailCookie);
String url = "WEB-INF/view/registration_confirmation.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
I'm new to web development and I just need a push in the right direction to fix this issue.
I'm using glassfish and mysql.
Just fixed the problem – moved all the files to a new project and manually created the web.xml and it's is working fine now. Thanks #ErnestFriedman-Hill