I'm trying to make a register page into my servlet project.
If the username is already taken, I want to show an error message.
Heres my code :
String uname=request.getParameter("uname");
String pass=request.getParameter("pass");
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/covid","root","fbfbfb333*");
String query = "SELECT * FROM users WHERE username = ?";
pstmt = (PreparedStatement) con.prepareStatement(query);
pstmt.setString(1, uname);
rs = pstmt.executeQuery();
if(rs.next()) {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
} else {
System.out.println("Username " + uname + " already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
But when I add a new users , it says " username already taken " whether it exist or not.
What should I do?
Switch the condition, if there is a result set data means that the username is taken, else insert new username
if(rs.next()) {
System.out.println("Username " + uname + " already exists.");
} else {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
}
Related
Good day ,
While I am trying to update data after inserting new ones in the database,
This message is showing for me
can not issue executeupdate() for selects
I have checked tutorialspoint.com and codejava and the codes for both update and select are the same and the program is issuing the statement above
Here is my codes
String Sql="Select * from training where trainID=? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("traTitle"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
String Sql="Select * from training where traTitle =? ";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
while (rs.next()){
jTextField2.setText(rs.getString("trainID"));
}
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
String Sql= "UPDATE training SET traTitle ='"+ jTextField2.getText()+"', Type = "+(String) jComboBox1.getSelectedItem()+"', SDate = '"+sqlDate+"', Edate = '"+sqlDate2+"', location = '"+jTextField3.getText()+"',provider = '"+(String) jComboBox1.getSelectedItem()+"',related = '"+jTextArea1.getText()+"',benefits = '"+jTextArea2.getText()+"'important = '"+jTextArea3.getText()+"' WHERE trainID = "+jTextField1.getText()+"";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
Statement st = con.createStatement();
int i =ps.executeUpdate();
if (i>0)
{
JOptionPane.showMessageDialog(null, "Data is Saved");
}
else {
JOptionPane.showMessageDialog(null, "Data is not Saved");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
JOptionPane.showMessageDialog(null, e);
}
Any Solution ?
Statement st = con.createStatement();
int i = ps.executeUpdate();
The problem is here. You are creating a new, unused, Statement, and then trying to call executeUpdate() on the previously prepared statement, which was a SELECT.
This would have been avoided by correctly scoping the variables concerned as method-local. None of them should be instance or static members.
String user = request.getParameter("uname");
String pwd = request.getParameter("pass");
String pwd1 = request.getParameter("pass");
String pwd2 = request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/logindb";
Connection con = DriverManager.getConnection(url, "root", "root");
String sql = "select * from register";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
ResultSet rs = ps.executeQuery();
if(rs.next())
{
sql = "update register set pass=? where uname=? ";
ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
ps.executeUpdate();
out.println("password changed");
}
}
catch(Exception e)
{
out.println(e);
}
This Is my code and it will show me an error like this
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).**
Here:
String sql = "select * from register";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
You are trying to set parameters that aren't there. Looks like a copy-and-paste error. Those last 2 lines shouldn't be there.
I Am currently working on a small project for myself which allows me to create new user to a database. Everything was going well until I noticed that one of my brackets on the code is displaying an error. Which is strange due to I checked I closed all of my brackets. If someone could see the missing bracket or help me fix the current ones it would be very useful.
JButton NewUserBtn = new JButton("Create New User");
NewUserBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Username = userText.getText();
String Password = passText.getText();
String Email = emailText.getText();
String cid = cidText.getText();
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
}
else {
try {
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
}
catch (Exception e3) {
e3.printStackTrace();
}
}
}
});
The Bracket is the second to last one. Is says I should add finally but I do not understand why? Thanks for anyone who can solve this problem I'm having.
It's enough to only have one try statement. The code below should be working fine.
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
} // if
else {
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
} // else
} // try
catch (Exception e3) {
e3.printStackTrace();
} // catch
You dont catch or finally your first try block.
You have added try-catch combination to inner try statement just above PreparedStatement, but outer try statement is missing catch or finally. See my comments below:
JButton NewUserBtn = new JButton("Create New User");
NewUserBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Username = userText.getText();
String Password = passText.getText();
String Email = emailText.getText();
String cid = cidText.getText();
try { //But it doesn't have either catch or finally
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
}
else {
try { //You have catch for this
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
}
catch (Exception e3) {
e3.printStackTrace();
}
}
}
});
I want to retrieve a users name from the username and password that they have entered into textfields. i want to pass these values as parameter to method which will then identify the users name for printout. please help. something like this...
public void getUser(String username, String password)throws SQLException{
String qry = "SELECT UserName From USER....";
Connection con = null;
PreparedStatement stmt = null;
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.executeUpdate();
If not is an update or an insert, don't use executeUpdate()
You must use executeQuery().
Try this:
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT UserName From USER where username=? and password=?";
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("UserName"));
}
...
Regards
Assuming that you want to get the user's full name from db and your table structure is something like this:
fullname | username | password
you could do the following:
Connection c = null;
PreparedStatement s = null;
try {
c = DriverManager.getConnection("URL");
s = c.prepareStatement("SELECT fullname FROM user WHERE username=? and password=?");
s.setString(1, username);
s.setString(2, password);
ResultSet rs = s.executeQuery();
if(rs.next())
return rs.getString("fullname");
return null; // no user found!
} catch(SQLException e) {
System.err.println(e.getMessage());
} finally {
// close s and c
}
Note: This assumes that the password that is passed to the method is in the same "form" as it is stored in db (i.e. either plain text or hashed (+salted))
try this its very simple example
private boolean validate_login(String id,String password) {
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again