im having a problem with my servlet whenever it was open from my JSP which is ShowPurchasingItems.jsp it will not go to the next JSP.
here is my ShowPurchasingItems.jsp
http://jsfiddle.net/0g3erumm/
and here is my Servlet that wont open my next JSP
package connection;
import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
#WebServlet("/CheckOutServlet")
public class CheckOutServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String User = (String) session.getAttribute("username");
String id = (String) session.getAttribute("stockIdToPurchase");
float price = (float) session.getAttribute("UnitPriceToPurchase");
int stock = (int) session.getAttribute("OnStockToPurchase");
int quantityOrdered = (int) session.getAttribute("purchaseQuantity");
float totalPrice = price * quantityOrdered;
int newStock = stock - quantityOrdered;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "jdbc:mysql://localhost:3306/inventory";
String user = "root";
String password = "password";
String query = "INSERT INTO purchases (username,stockId,price,quantityOrdered,totalPrice) VALUES ('"+User+"', '"+id+"', "+price+", "+quantityOrdered+", "+totalPrice+");";
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
if(rs.next())
{
String encodedURL = response.encodeRedirectURL("ShowInventoryList.jsp");
response.sendRedirect(encodedURL);
}
}
catch(Exception e)
{
out.println("There is an error here");
}
finally
{
out.close();
try
{
rs.close();
stmt.close();
conn.close();
}
catch (Exception e)
{
out.println("There is no error here");
}
}
}
}
it would keep on catching error on this statment out.println("There is an error here"); and i am stuck in here i dont know what else is wrong with my program hope someone can help me.
You're committing a cardinal sin by swallowing the exception and thus losing all information that may help you get to the bottom of your problem!
You should change how your exceptions are handled, at the very least you should be dumping the stacktrace:
catch(Exception e) {
out.println("There is an error here");
e.printStackTrace();
}
Once you have the stacktrace you'll be in a much better situation when it comes to diagnosing the problem (or asking more specific questions)!
Edit - Based on the exception posted in the comment:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery()
Is being thrown because you are performing an update using the query method. You should change your code to this:
int updateCount = stmt.executeUpdate(query);
if(updateCount > 0) {
String encodedURL = response.encodeRedirectURL("ShowInventoryList.jsp");
response.sendRedirect(encodedURL);
}
executeQuery executes the given SQL statement, which returns a single ResultSet object.
You're making INSERT, which doesn't return anything. I suppose that's why you're getting an exception.
I'd recommend to use PreparedStatement where you can bind variables and prevent SQL injection + some DB work faster with prepared statements, and executeUpdate instead of executeQuery
PreparedStatement stmt = null;
...
String query = "INSERT INTO purchases (username,stockId,price,quantityOrdered,totalPrice) VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, username);
...
int inserted = stmt.executeUpdate();
if (inserted > 0) {
// there was a successfull insert
...
There are a lot of examples on the Internet. For example: http://www.mkyong.com/jdbc/how-to-insert-date-value-in-preparedstatement/
Related
Can someone please tell me what is wrong to my query.
I have textbox to update the occupantname but it doesn't work, Only Status works.
String gOccupied = "Occupied" ;
String query = "UPDATE `rooms` SET `occupantname` = '"+txtFirstNames.getText()+"' , `status`='"+gOccupied+"' WHERE roomnumber = " +CBRoomNumber.getSelectedItem();
executeSQlquery(query,""+" Updated");
Can someone please tell me what is wrong to my query. i have textbox
to update the occupantname but it doesn't work, Only Status works.
Don't use direct MySql SQL with these special characters `
String query = "UPDATE rooms SET occupantname =
'"+txtFirstNames.getText()+"' , status='"+gOccupied+"' WHERE
roomnumber = " +CBRoomNumber.getSelectedItem();
Blockquote
Instated Use below SQL
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
private static PreparedStatement preparedStmt = null;
private static Connection connection = null;
public static void main(String[] args) {
String gOccupied = "Occupied";
String occupantname = txtFirstNames.getText();
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
try {
executeSQlquery(query, occupantname, gOccupied, "Updated");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void executeSQlquery(String query, String occupantname, String gOccupied, String status) throws SQLException {
try {
// create a java mysql database connection
String myDriver = "org.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
connection = DriverManager.getConnection(myUrl, "username", "password");
preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, occupantname);
preparedStmt.setString(2, gOccupied);
preparedStmt.setInt(3, 101);
// execute the java preparedstatement
preparedStmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//finally block used to close resources
if (preparedStmt != null) {
connection.close();
}
if (connection != null) {
connection.close();
}
}
}
}
It is generally a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
SQL select statement with where clause
I have 2 HTML Forms:
1. Register/Login
2. After User gets Login, He used to update details of him.
I used MySql database in order to save Login details of User. And also i have another table for updating details of him after his login.
I got succeed in register/Login process., But problem arises here.,., I dont know how to proceed further., After his Login., the user should be able to update his details in his respective table.
Here is My Login Servlet which takes information from First Main Login Form After User gets Login., Then there is another HTML Form where user enter his personal details., which is stored in another table., There Problem arises., I'm unable to process details of User in second table
Login Servlet:
package com.ea.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pass = request.getParameter("pass");
String mem = request.getParameter("mem");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/EATWO","root","");
Statement statement = (Statement) con.createStatement();
ResultSet rs = statement.executeQuery("SELECT * from singer where name='" + name + "'");
String duplicate = null;
while(rs.next()){
duplicate = rs.getString(1);
}
if(duplicate == null){
PreparedStatement ps=con.prepareStatement
("insert into Singer(name,password,member) values(?,?,?)");
ps.setString(1, name);
ps.setString(2, pass);
ps.setString(3, mem);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
}
else{
//request.getRequestDispatcher("/register.html").forward(request, response);
//request.setAttribute("error","Invalid Username/password");
request.getRequestDispatcher("/register_err.html").forward(request, response);
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
This code is the effected one to say...I want this servelt to get corrected according to your suggestions..Here is the Second SubForm., Where after User gets login., This code helps user to store his personal details., But i got stuck with this.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pass = request.getParameter("pass");
String mem = request.getParameter("mem");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/EATWO","root","");
Statement statement = (Statement) con.createStatement();
ResultSet rs = statement.executeQuery("SELECT * from singer where name='" + name + "'");
String duplicate = null;
while(rs.next()){
duplicate = rs.getString(1);
}
if(duplicate == null){
PreparedStatement ps=con.prepareStatement
("insert into Singer(name,password,member) values(?,?,?)");
ps.setString(1, name);
ps.setString(2, pass);
ps.setString(3, mem);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
}
else{
//request.getRequestDispatcher("/register.html").forward(request, response);
//request.setAttribute("error","Invalid Username/password");
request.getRequestDispatcher("/register_err.html").forward(request, response);
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database Connection
con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/EATWO","root","");
For pool sake, do you believe in pooling objects!?, worse you do not close the Connection, neither Statements, neither ResultSets!
ResultSet rs = statement.executeQuery("SELECT * from singer where
name='" + name + "'");
Too dangerous(sql inject), use the PreparedStement instead as you did with the rest.
This
String duplicate = null;
while(rs.next()){
duplicate = rs.getString(1);
}
if(duplicate == null){
PreparedStatement ps=con.prepareStatement
("insert into Singer(name,password,member) values(?,?,?)");
ps.setString(1, name);
ps.setString(2, pass);
ps.setString(3, mem);
int i=ps.executeUpdate();
if(i>0){
out.println("You are sucessfully registered");
}
}
Could be like this
if(!rs.next()){
PreparedStatement ps=con.prepareStatement
("insert into Singer(name,password,member) values(?,?,?)");
ps.setString(1,name);ps.setString(2,pass);ps.setString(3,mem);
int i=ps.executeUpdate();
if(i>0){
response.redirect("<<update_cgi_path_here>>");return;
}
}
After you successfully register the user, redirect him to update page using redirect(path:String):void method, like below
response.redirect("/update__info");return;
Awesomeness:
You select one record, and then insert one record if the first one is not exist!C'mon what kinda logic is this!, the whole record insertion(persisting new user) should be done by one external/SQL call.Your code has very good potential for data-inconsistency(as far as I don't know what is going on in sql data structure) because it's not thread-safe.
Just like registration page, you may have a html page which user provide its information, simply get the parameters from request(just like register) and update the user data over back-end data source.But please first have a database connection pool, use PreparedStatement over Statement(if you need to set something), have some backend sql function which checks and insert users(rather than multiple calls), believe in closing Closeables(simply using try(<<closeable>>){})
I was trying to display the rows in the database using Java. My idea is to sort the rows in the database and display them in 3 columns and infinite rows. This is what I have. When I run it, I couldn't see any output. Where did I go wrong?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class Rows {
public static void main(String[] args) throws SQLException,ClassNotFoundException
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
String sql = "select * from site order by fname;";
stmt.execute(sql);
} catch (ClassNotFoundException e) {
System.err.println("Could not load database driver!");
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}
The database table I have is
datas(id int, fname varchar(20)
Statement stmt = connection.createStatement();
String sql = "select id, fname from site order by fname;";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
int id=rs.getInt("id");
.............
}
Reference: Retrieving and Modifying Values from Result Sets
The code should obtain a ResultsSet and iterate through it.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
//You shouldn't need the semi-colon at the end
String sql = "select * from site order by fname;";
//missing piece
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}
I write a code in servlet for login checking I don't know why I get an error like java.sql.SQLException: No data found, if I had not commented out the String s4 = rs.getString(1) and out.println(s4) line if I commented out this lines I did not get any error.
Why do I get an error like this? I cannot find out the answer.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class login extends HttpServlet {
Connection conn;
Statement stmt;
ResultSet rs;
String s = "";
public void init() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("Jdbc:Odbc:edsn");
s = "Your information is connected ......";
} catch (Exception e) {
s = "Exception 1....." + e.getMessage();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
out.println(s);
try {
String ID = req.getParameter("T1");
String query = "select * from user_db ";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
out.println("user" + " " + "pass");
while (rs.next()) {
try {
if ((rs.getString(1)).equals(ID)) {
String s4 = rs.getString(1);
out.println(s4);
out.println("<html><body><h> login Pass.....:(</h></body></html>");
}
} catch (Exception e) {
out.println(e);
}
}
} catch (Exception e) {
out.println("Unable To Show the info... . . ." + e.getMessage());
}
}
}
Why write the code like this ? It's very wasteful going over the whole table...
The IO alone...
Why not change to this:
ResultSet rs = null;
PreparedStatement st = null;
try {...
String ID = req.getParameter("T1");
String query = "select 1 from user_db where col_name = ?";
st = conn.prepareStatement(query);
st.setString(1, ID);
rs = st.executeQuery();
if (rs.next()) {
out.println(ID);
out.println("<html><body><h> login Pass.....:(</h></body></html>");
}
..
} finally {
if (rs != null) try { rs.close();}catch (Exception e) {}
if (st != null) try { st.close();}catch (Exception e) {}
}
notice prepared statements are cached and better for frequent use
you let the db do what its good at - search the data
select 1 instead of select * does not bring back data you dont really need
jdbc works harder the more columns and data in general you return, so only get what you
need
and add a finally block to always close your db connections properly
Calling methods on Connection, Statement, or ResultSet depend on which JDBC driver you've loaded. All the values of the ResultSet could be set as soon as the query is made, or they could be retrieved from the database as they're needed, depending on the implementation of the driver.
The JdbcOdbcDriver throws an SQLException after calling getString for a second time. This can be worked around be storing the values in Strings instead of making multiple calls, or by switching to a different driver.
I have a null pointer exception in
ResultSet rs = aStatement.executeQuery(Query); // it can't be executed
my code is like this :
public static boolean testLogin(String user, String password) throws SQLException {
String Query = "select * from TBL_Users where userName = '" + user + "' and passWord = '" + password + "' ";
ResultSet rs = aStatement.executeQuery(Query);
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true;
}
return false;
}
}
Most likely aStatement is null.
Sounds like you think aStatement should not be null, but it is.
This is bad JDBC code, for many reasons:
No cleanup of resources.
Doesn't use PreparedStatement
Keeps creating the query string over and over again instead of using a static variable
Doesn't follow Java coding standards ("Query" should be "query")
Here's another way to write it. Start with an interface:
package persistence;
import java.sql.SQLException;
public interface CredentialDao
{
boolean isValidUser(String username, String password) throws SQLException;
}
Write an implementation:
package persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CredentialDaoImpl implements CredentialDao
{
private static final String CREDENTIAL_QUERY = "SELECT COUNT() FROM USER WHERE USERNAME = ? AND PASSWORD = ?";
private Connection connection;
public CredentialDaoImpl(Connection connection)
{
this.connection = connection;
}
public boolean isValidUser(String username, String password) throws SQLException
{
boolean isValidUser = false;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = this.connection.prepareStatement(CREDENTIAL_QUERY);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
while (rs.next())
{
int count = rs.getInt(1);
isValidUser = (count > 0);
}
}
finally
{
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return isValidUser;
}
}
The aStatement variable is apparently null, please validate that it is correctly set. You should consider read the Java Naming Conventions and make sure you use the lower camel case for variables and java bean conventions.
For code snippets in stackoverflow if they are not self-explanatory, you should obey the rules of the SSCCE, this will help you to get more and better answers. Also you should provide a stack trace with the occured exception.
Use prepared statements.
Connection con = ...; // obtain connection here
PreparedStatement pstmt = con.prepareStatement("select * from TBL_Users where userName = ?'");
pstmt.setInt(1, userName);
ResultSet rs = pstmt .executeQuery();
...
// do clean up here
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true; // Huh? What?
}
What is info refering to and why is there a return imediatly after the assignments?