Unable to execute the update query in java servlet - java

I am doing Change password i need to update the old password. based on old password i need to get record and then updating record but here is the problem when i got record i trying to update it shows null in message
My code:
public String ResetPwd(String NewPwd, String name,String oldpwd)
{
String Pass="Select * from Users where Password='"+oldpwd+"' and UserId='"+name+"'";
String UpdateQuery="update Users set Password='"+NewPwd+"' where UserId='"+name+"'";
try{
currentCon = ConnectionManager.getConnection();
st=currentCon.createStatement();
rs = st.executeQuery(Pass);
if(rs.next())
{
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
int i=ps.executeUpdate();
ps.close();
if(i>=1)
{
msg="Password Changed Successfully";
}
}
else{
msg="Old Password Not Match Please Enter Correct Password..!";
return msg;
}
}catch(Exception ex){}
return msg;
}

msg is null because probably some exception is being thrown and it doesn't get set to anything. As #CraigR8806 said don't just ignore the exceptions you catch but print them at least.
The exception being raised is probably SQLException since you are calling
executeUpdate on an already closed preparedStatament in this point
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
ps.executeUpdate();
ps.close();
int i=ps.executeUpdate();
ps.close();
Since there is no reason for a second update change it to:
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
int i=ps.executeUpdate();
ps.close();
as a side note use try with resources as it helps with closing those resources

Related

MySQL not pushing insert into database with netbeans

Recently I'm just learning some HTML, JSP and servlets for a university project, the thing is that I made a database into MySQL Workbench with id primary key, auto increment , then some fields like username, password, firstname, lastname, and so on.
The goal is to make a login page and register page, for some reason if I push data with MySQL Workbench into the database it will let me retrieve it with my login form and my select statment, but for some reason I'm doing the same thing with register but in this case with the query INSERT.
So, after research, I did preparestatment and changed the executeQuery to executeUpdate and everything, but my log says a nullPointerException somewhere, I know it may be a simple and silly error that I'm not seeing, but I'm new at this. This is what U have made so far to insert data into my database:
public static UserBean registarUsuario(UserBean bean){
//preparing some objects for connection
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("Error al cargar el driver");
System.out.println(ex.getMessage());
}
String firstname = bean.getFirstName();
String lastname = bean.getLastName();
String username = bean.getUsername();
String password = bean.getPassword();
boolean admin = bean.isAdmin();
int tipo = bean.getType();
String insertQuery =
"insert into idusuario (firstname,lastname,username,password,admin,tipo) values ('"+firstname+"','"+lastname+"','"+username+"','"+password+"','"+admin+"','"+tipo+"')";
System.out.println("Firstname is " + firstname);
System.out.println("Surname is " + lastname);
System.out.println("Query: "+insertQuery);
try
{
//connect to DB
currentCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/usuarios", "root", "admin");
rs = stmt.executeQuery(insertQuery);
...
My output:
Info: Query: insert into idusuario
(firstname,lastname,username,password,admin,tipo) values
('jhon','marston','jmar','123','true','0') Info: Error :
java.lang.NullPointerException
The thing is that Netbeans doesn't even tell me where the NPE is happening so I'm kind of confused, I don't know if the query is wrong or if something else is, because as I can see in my output, the query seems ok.
I leave you here my database structure
You are assigining the stmt as null and never initializing it.
Statement stmt = null;
ResultSet rs = null;
Then you are trying to use it:
rs = stmt.executeQuery(insertQuery);
You will need to do something like this before you use it:
PreparedStatement stmt=currentCon.prepareStatement(yourQuery);
So, after research, i did preparestatment and changed the executeQuery
to executeUpdate and everything, but my log says a
nullPointerException somewhere, i know it may be a simple and silly
error that im not seeing, but understand that im new at this. this is
what i have made so far to insert data into my database
When we use insert,update or delete we need to use executeUpdate.
When we use select we need to use executeQuery.
In your example you are doing executeQuery for an insert. This is wrong. You need to use this:
rs = stmt.executeUpdate(insertQuery);
You're getting a NPE because you are trying to retrieve the results where there are none.
Here is a nice thing to do to help you reduce boilerplate code... (so you don't have to keep repeating yourself with db initialization values)
Create a class for your database connection:
public class DBConnection {
private static String url = null;
private static Connection conn = null;
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://localhost:3306/usuarios";
conn = DriverManager.getConnection(url,"root","admin");
} catch (Exception e) {
System.out.println(e);
}
return conn;
}
}
Now you can use this in all your other classes like this:
public static UserBean registarUsuario(UserBean bean){
try(Connection conn= DBConnection.getConnection()){
PreparedStatement pst = conn.prepareStatement("insert into idusuario (firstname,lastname,username,password,admin,tipo) values (?,?,?,?,?,?);");
pst.setString(1, bean.getFirstName());
pst.setString(2, bean.getLastName());
pst.setString(3, bean.getUserName());
pst.setString(4, bean.getPassword());
pst.setBoolean(5, bean.isAdmin());
pst.setInt(6, bean.getType());
pst.executeUpdate();
}catch (SQLException e) {
e.printStackTrace();
}
}

how to validate a username value with mysql and java to avoid duplicate user name

good day, i have a problem with this method, for some reason it gives me an error. "Java.sql.SqlException: statement is not executing". But it checks if the value is duplicate and prompts the error as the method below show. This has stopped my registration from completing. thanks for your help
public static void UserExists(String y){
try{
query = " select * from MailRegister where Username=?";
pst = connect.prepareStatement(query); //passes my query to java predefined prepared statement
pst.setString(1, Username.getText()); //passes the value of the username to the prepared statement
rs = pst.executeQuery(); //this would execute the query passed in the prepared statement
if(rs.next()){
JOptionPane.showMessageDialog(null, " Sorry This Username is Taken");
}
pst.close();
rs.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);//shows error dialog
}
}
You probably get this error because your objects are not closed properly all the time. Your connect is breaking. A good practice is to open and close the connection when required to prevent leaks.
In the code above, pst.close(); and rs.close(); should be in a finally.
Or even cleaner, the prepared statement should go inside a :
try (pst = connect.prepareStatement(query)) {...}
That way you don't have to close it yourself, the JVM will handle it for you.

java.sql.SQLException: Illegal operation on empty result set. when authenticating

What I'm trying to do is:
Accept username(uname) and password(passw) as an input from the user.
Using ResultSet, retrieve the only tuple, to which username in the database and username given by user suits. This tuple will contain username and password.
If the password given by user also suits the password in the database, the display the message that both creadentials are correct else one of them is wrong.
Everything works fine except in one case. When the username itself is wrong, the mysql will not find the attribute at all and will give this error: java.sql.SQLException: Illegal operation on empty result set.
The code is:
ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String uname=jf1.getText();
String passw=jf2.getText();
String n;
String m;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/authentication?" + "user=root&password=letmein");
PreparedStatement stmt=conn.prepareStatement("Select * from admin where id = ?");
stmt.setString(1,uname);
ResultSet rs=stmt.executeQuery();
rs.next();
n=rs.getString("id");
m=rs.getString("pass");
conn.close();
if(n.equalsIgnoreCase(uname) && m.equalsIgnoreCase(passw))
{
JOptionPane.showMessageDialog(null,"Username and password is correct");
}
else
{
JOptionPane.showMessageDialog(null,"Username or password is not correct");
}
}
catch(Exception ex)
{
System.out.println(ex);
}
}//end of actionperformed
});//end of actionlistener
Is there any way I can do both operations at a time (before closing the connection with database)?. If not, what's the alternative method?
You are supposed to use the result of rs.next() :
if (rs.next()) {
n=rs.getString("id");
m=rs.getString("pass");
}
If rs.next() returns false, this means the query returned no rows.
#Eran mentioned the error by which a wrong id would yield an empty result set on which fields were gotten.
I still have small remarks:
Try-with-resources take care of closing even in case of an exception or returning.
For a local database you can send the password to SQL.
Best to store passwords encrypted, when ever your database should get stolen.
Thus:
boolean loggedIn = false;
try (PreparedStatement stmt =
conn.prepareStatement("SELECT 1 FROM admin WHERE id = ? AND pass = PASSWORD(?)")) {
stmt.setString(1, uname);
stmt.setString(2, passw);
try (ResultSet rs = stmt.executeQuery()) {
loggedIn = rs.next();
} // Closes rs.
} // Closes stmt.

Null Pointer Exception in Method Which Sets the Parameters for Prepared Statement

I Have Looke over the internet that from Last 12 hours , and found that too many Users are facing that Problem , But None of them are Able to get Rid of That,
I hav Created a JDialog , Which have TextFields, and i am Trying to get Input From those text Fields, and Store That In DataBase,
But is Givi the Following Exception.
Exception occurred during event dispatching:
Connection ok
Adnan
java.lang.NullPointerException
at srvrDataBaseClass.setPersonStatement(srvrDataBaseClass.java:90)
at srvrDataBaseClass.insertPerson(srvrDataBaseClass.java:71)
at EnrollmentForm.setPerson(EnrollmentForm.java:90)
Here is the Code Where the StackTrac is Pointing ,
public void setPersonStatement(String nm,String fn,String cn,String add, byte[] fpt) {
String Sql = "INSERT INTO PERSON (NAME, FNAME, CNIC, ADDR, FPT) VALUES ( ?,?,?,?,?)";
try {
if(con==null){
System.out.println("Connection error"); <---------------- Connection is Not Closed
}
else {
System.out.println("Connection ok"); <------Connection ok
}
con.prepareStatement(Sql);
System.out.println(nm); <----- This is Line :90, But You can see its not Null, as the Value 'Adnan' is printed on cmd,
pst2.setString(1, nm);
pst2.setString(2, fn);
pst2.setString(3, cn);
pst2.setString(4, add);
pst2.setBytes(5, fpt);
pst2.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("SQL Error");
e.printStackTrace();
}
}
So Any One Who can tell me , Whats Wrong with my Code
Note: DataBase is SQL Server 2008,
Did you mean to do
pst2 = con.prepareStatement(Sql);
? It seems like pst2 is null and will remain so in
pst2.setString(1, nm);
which probably actually throws the NPE.
Check out the javadoc for the method you are trying to use.
con.prepareStatement(Sql);
is not assigned to a proper PreparedStatement Variable,
write as
pst2= con.prepareStatement(Sql);

help needed (corejava)

I m getting except1 on running this code.Please see if there is any mistake within the try block....
Try
{
pst=con.prepareStatement("SELECT Name,Roll,Semester,Address,Phoneno," +
"E-mailId,Gender,DOB,Result FROM stud WHERE Roll = ?");
pst.setString(1,s2);
ResultSet rs=pst.executeQuery();
while(rs.next())
{
s2=rs.getString("Roll");
String s1=rs.getString("Name");
String s3=rs.getString("Semester");
String s4=rs.getString("Address");
String s5=rs.getString("Phoneno");
String s6=rs.getString("E-mailId");
String s7=rs.getString("Gender");
String s8=rs.getString("DOB");
String s9=rs.getString("Result");
t1.setText(s1);
t2.setText(s2);
t3.setText(s3);
t4.setText(s4);
t5.setText(s5);
t6.setText(s6);
t7.setText(s7);
t8.setText(s8);
t9.setText(s9);
}
con.commit();
con.close();
}
catch(SQLException e2)
{
System.out.println("except1");
}
caveat: my Java is rusty -
don't know if field names can contain hypens, depends on the database
print the exact exception that you're getting
why are you doing a commit on a SELECT?
Make Sure data type of "Roll" Atrribute in Database is Character(n).
if it is integer/number then use this
pst.setInt(1,Integer.parseInt(s2));
Make sure you use VARCHAR data type for all attributes in database. If it is not the case then change your code according to these data types.
And print exception stack trace (e2.printStackTrace()) in catch block for getting exact reason for the exception.
Thanks
Try
{
pst=con.prepareStatement("SELECT Name,Roll,Semester,Address,Phoneno," +
"E-mailId,Gender,DOB,Result FROM stud WHERE Roll = ?");
pst.setString(1,s2);
string s2 = '123123'; //pass the required value to Query
ResultSet rs=pst.executeQuery();
while(rs.next())
{
//String s2=rs.getString("Roll");
String s1=rs.getString("Name");
String s3=rs.getString("Semester");
String s4=rs.getString("Address");
String s5=rs.getString("Phoneno");
String s6=rs.getString("E-mailId");
String s7=rs.getString("Gender");
String s8=rs.getString("DOB");
String s9=rs.getString("Result");
t1.setText(s1);
t2.setText(s2);
t3.setText(s3);
t4.setText(s4);
t5.setText(s5);
t6.setText(s6);
t7.setText(s7);
t8.setText(s8);
t9.setText(s9);
}
con.commit(); // use commit only when you are doing create/update operations
con.close();
}
catch(SQLException e2)
{
System.out.println("Error Information");
e2.printStackTrace();// this method display the error information
}

Categories

Resources