How to delete data from database using JDBC - java

I am trying to make a form where sellers can insert new items, new category and delete items. Now I have problem with DELETE.
This is my code and if somebody know how to fix it please help.
String id = "42";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/projekat","root","");
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ? ;");
prepared_statement.setString(1, id);
int result_set = prepared_statement.executeUpdate();
if (result_set > 0)
{
System.out.println("Deleted");
}
else
{
System.out.println("Can't delete");
}
} catch (Exception ex) {
System.out.println(ex);
}

Try this:
String id = request.getParameter("id");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/projekat","root","");
PreparedStatement prepared_statement = null;
String strQuery = "DELETE FROM artikli WHERE id= ?";
prepared_statement = connection.prepareStatement(strQuery);
prepared_statement.setString(1, id);
int result_set = prepared_statement.executeUpdate();
if (result_set > 0)
{
// System.out.println(result_set);
response.sendRedirect("Prodaja2.jsp");
}
else
{
// System.out.println(result_set);
response.sendRedirect("Prodaja2.jsp?error=Can'tDelete");
}
} catch (Exception ex) {
out.print(ex);
} finally {
try {
stmtProd.close();
connection.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
In your code the semicolon after the query may be conflicting. And also don't forget to close the connections in the finally block created because it may lead to resource leak and connection will remain active even if the user logs out.

One error is here, that is in your syntax
Change the code
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ? ;");
to
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ?");
If there is no other errors, Check value in id, there is a chance of null value.

Related

Servlet not updating value in database

I'm trying to create a basic password reset system. I'm creating an unique token for each user, storing in database and retrieving that token value in url like: http://localhost:8080/login/reset-password.jsp?token=0d1eaa1a-869c-4f40-8437-a3cdaeddf497
The problem here is that I'm trying to update the password in the database but the value isn't updated. It displays that the password is changed, but nothing happens in database. Please help.
Here's my servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String password = request.getParameter("password");
String token = request.getParameter("token");
ForgotPasswordHandler.UpdatePassword(password, token);
String message = "Password changed!";
request.setAttribute("message", message);
request.getRequestDispatcher("reset-password.jsp?token=" + token).forward(request, response);
}
Here's my method in class ForgotPasswordHandler.java:
public static void UpdatePassword(String password, String token) {
try
{
if (con == null){
System.out.println("Failed connection");
}else{
PreparedStatement ps = con.prepareStatement(
"UPDATE user SET password = ? WHERE reset_token = ?");
ps.setString(1,password);
ps.setString(2,token);
ps.executeUpdate();
ps.close();
}}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
Your connection may have autoCommit turned off. If that is the problem you can fix it with code like this:
if (!con.getAutoCommit()) {
con.commit();
}
One other thing to note is that if the call to ps.executeUpdate() fails, the prepared statement will not be cleaned up. To avoid that problem move the close to the finally block. Here is what the full code would look like:
PreparedStatement ps = null;
try
{
if (con == null){
System.out.println("Failed connection");
} else {
ps = con.prepareStatement(
"UPDATE user SET password = ? WHERE reset_token = ?");
ps.setString(1,password);
ps.setString(2,token);
ps.executeUpdate();
if (!con.getAutoCommit()) {
con.commit();
}
}
}
catch (Exception e) {
e.printStackTrace(System.out);
}
finally {
if (ps != null) {
ps.close();
}
}

Inconsistencies with mySQL delete query

I've encountered an some inconsistencies regarding the results from an SQL query.
Here is the query which I'm using as a prepared statement.
delete ROLE_USER_MAP
from ROLE_USER_MAP inner join ROLE_MANAGER on ROLE_USER_MAP.R_ID=ROLE_MANAGER.R_ID
where ROLE_USER_MAP.U_ID= ? and ROLE_MANAGER.M_ID= ?
Here is how I calling the prepared statement in my Java application.
public void deleteRoles(String mID, String uID) throws OperationFailedException
{
Connection conn = null;
try
{
conn = this.getConnection();
this.deleteRoles(mID, uID, conn);
}
catch (Exception e)
{
AdminLogger.error(this.getClass(), e);
throw new OperationFailedException("Failed to remove roles for user.");
}
finally
{
try
{
conn.close();
}
catch (Exception e)
{
}
}
}
private void deleteRoles(String mID, String uID, Connection conn) throws SQLException
{
PreparedStatement stmt = null;
try
{
stmt = *retrieving ps*
stmt.setString(1, uID);
stmt.setString(2, mID);
int i = stmt.executeUpdate(); // returns 1 here
if (i < 1)
{
throw new SQLException("Failed to remove roles for user.");
}
} finally
{
stmt.close();
}
}
It runs fine locally and in SSMS with all rows fitting the where clause being deleted but when I try to deploy it to my hosted server, only the first row in the table is being deleted.
Can anyone help me with this?
Thanks in advance.

Else not working in If statement when using specific query for SQL

I have to connect a database to my codes to check a pin code. I have managed to make it but I'm having some problem to make the else part of the if statement to work. I think its the query part which is causing the problem as when I change the if..else statement it works perfectly.
If there is any other way to write this query to get the same result please let me know
thank you
public void getOperation() {
{
Connection conn = null;
String query = "SELECT pin FROM customerdetails WHERE pin='"+Pin+"'";
Statement stmt = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "user","#1234#");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String password = rs.getString("pin");
if (Pin.equals(password)) {
PinCheck = "Pin OK";
} else
{
PinCheck = "Invalid Pin";
}
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (stmt != null) {
}
if (conn != null ) {
//conn.close();
}
}
}
Having this
String query = "SELECT pin FROM customerdetails WHERE pin='"+Pin+"'";
while (rs.next()) {
String password = rs.getString("pin");
if (Pin.equals(password)) {
PinCheck = "Pin OK";
} else
{
PinCheck = "Invalid Pin";
}
}
makes little sense, as you will always have equal Pin - because you are querying for it. Check for results count. 1== Pin matches, 0== pin invalid.

MySQL query returns empty resultset

Currently I'm writing a very simple Java Servlet which will only execute one query and print the results.
The issue I'm facing is that it's working locally using JBoss as AS. When I deploy it to TomCat remotely, the same query is returning no results.
My observations:
The table has data. I've used SQuirrelSQL to check (about 100 rows);
Using the mysql cli it is also returning no results;
The code below returns "yes yes yes yes..." locally, but remotely only "go"
The code:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setHeader("Content-Type", "application/json");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace(res.getWriter());
}
List<Opportunity> opportunityList = new ArrayList<Opportunity>();
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/dbname", "dbuser", "dbpwd");
st = conn.createStatement();
rs = st.executeQuery(QUERY);
while(rs.next()) {
res.getWriter().print("yes ");
opportunityList.add(new Opportunity(rs));
}
} catch (SQLException e) {
opportunityList.clear();
res.getWriter().print("nooo ");
res.getWriter().println(e.toString());
} finally {
try {
res.getWriter().write("go ");
conn.close();
st.close();
rs.close();
} catch (Exception e) {
res.getWriter().write("noooo2");
res.getWriter().println(e.toString());
}
}
res.getWriter().write(new Gson().toJson(opportunityList));
}
EDIT-- The query:
SELECT o.ID, o.NAME, s.DESCRIPTION, pt.NAME, o.START_DATE, so.OWNER,
FROM SCOUT_OPPORTUNITY so
INNER JOIN OPPORTUNITY o ON so.OPPORTUNITY_ID = o.ID
INNER JOIN STATUS_DESC s ON s.NAME = o.STATUS_NAME
LEFT JOIN PROJECT_TYPE pt ON pt.ID = o.PROJECT_TYPE_ID
ORDER BY o.ID

Condition for redirecting to different page?

I wrote a servlet whose purpose is to login into the application only if the query executes...now what is the condition to be used for invalid username and id...I'm unable to write the condition..pls help me out...the servlet is...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl ","scott","tiger");
System.out.println("cnnection est");
int Id = Integer.parseInt(request.getParameter("id"));
String Name=request.getParameter("firstname");
boolean b=true;
//Connection con =JdbcConnectionUtil.getConnection();
PreparedStatement pst = con.prepareStatement("select * from login where id=? and firstname=?");
pst.setInt(1, Id);
pst.setString(2, Name);
ResultSet rs = pst.executeQuery();
if(rs!=null && rs.next())
{
//while(rs.next()){
PrintWriter pw = response.getWriter();
System.out.println("here");
pw.println("hello");
pw.println(rs.getInt(1));
pw.println(rs.getString(2));
pw.println(rs.getString(3));
}
//}
else
{
RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
}
//
}
catch(Exception ex){
ex.printStackTrace();
}
}
Using rd.forward will solve the problem I think.
How to forward requests from Servlet to JSP
First you check for the correct parameters and then you do the logic. Also do not forget to close statements and connections to avoid memory leaks.
Here is refactored code:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//get parameters from request
try {
String idParam = request.getParameter("id");
String name = request.getParameter("firstname");
//check if request contains such parameters
if (idParam == null || name == null) {
throw new IllegalArgumentException(
"Id and Name parameters must not be null.");
}
//try casting idParam to int
Integer id = null;
try {
id = Integer.parseInt(idParam);
} catch (NumberFormatException nfe) {
throw nfe;
}
PreparedStatement pst = null;
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl ", "scott", "tiger");
pst = con.prepareStatement(
"select * from login where id=? and firstname=?");
pst.setInt(1, id);
pst.setString(2, name);
//check if result returned any data
ResultSet rs = pst.executeQuery();
if (!rs.next()) {
throw new Exception(
"No such user for id: " + id + " and name: " + name);
}
PrintWriter pw = response.getWriter();
pw.println("hello");
pw.println(rs.getInt(1));
pw.println(rs.getString(2));
pw.println(rs.getString(3));
} catch (Exception ex) {
throw ex;
} finally {
try {
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException sqle) {
throw sqle;
}
}
} catch (Exception ex) {
ex.printStackTrace();
RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
rd.forward(request, response);
}
}
Something like that would be appropriate I think.

Categories