Im currently attempting to make a login system in Java and SQL and am currently getting an error.
PreparedStatement s1 = con.prepareStatement("SELECT * FROM dbo.Logins WHERE Username=? AND Password=?");
s1.setString(1,loginUsername);
s1.setString(2, loginPassword.toString());
ResultSet rs = s1.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "User Found");
}
else{
JOptionPane.showMessageDialog(null, "Error");
}
When I run that snippet of code it always displays the else part of the if/else and im not sure why. Thank in advance.
Edit: Yes the DB is populated with users.
Edit2: I changed the function to require two string args.
You can fetch number of rows available in your table for given query and if it is great than 0 it will execute User Found statement.
PreparedStatement s1 = con.prepareStatement("SELECT * FROM dbo.Logins WHERE Username=? AND Password=?");
s1.setString(1,loginUsername);
s1.setString(2, loginPassword.toString());
ResultSet rs = s1.executeQuery();
int rowCount = rs.last() ? rs.getRow() : 0; //Number of rows available in table for query
if(rowCount>0)
JOptionPane.showMessageDialog(null, "User Found");
}
else{
JOptionPane.showMessageDialog(null, "Error");
}
You must try to use while(rs.next()) instead of if(rs.next()).
If that does not work, does your DB (which you have mentioned is populated), contain those particular values of username and password that you are searching for ? If not, that may be the problem.
If that too does not work, you may have closed some objects (eg. s1.close() or con.close() ) where you shouldn't. For further help on that you will need to provide a more detailed flow of what you have done in the whole code.
public void Login(String user, String pass) throws ClassNotFoundException, SQLException{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
MainWindow mw = new MainWindow();
String userName = "<USERNAME>";
String password = "<PASSWORD>";
String url = "<URL>";
Connection con = DriverManager.getConnection(url, userName, password);
PreparedStatement s1 = con.prepareStatement("SELECT * FROM dbo.Logins WHERE Username=? AND Password=?");
s1.setString(1,user);
s1.setString(2, pass);
ResultSet rs = s1.executeQuery();
//int rowCount = rs.last() ? rs.getRow() : 0; //Number of rows
System.out.println("Name: " + user + "\nPass: " + pass);
if(rs.next())
JOptionPane.showMessageDialog(null, "User Found");
else{
JOptionPane.showMessageDialog(null, "Error");
}
con.close();
Related
So currently Im trying to do get the auto-incremented primary key by following this answer
Primary key from inserted row jdbc? but apparently the program can't even reach that line and the error appeared on the ps.executeQuery() line after debugging the program, the error it display was only "executeQuery" is not a known variable in the current context. that line, which didn't make sense to me. So how do I go pass this hurdle?
public static int createNewLoginUsers(String newPassword, String newRole) throws SQLException{
Connection conn = DBConnection.getConnection();
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
int id = 0;
try{
String sql = "INSERT into Login(password, role) VALUES(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, newPassword);
ps.setString(2, newRole);
ps.executeUpdate();
st = conn.createStatement();
rs = st.executeQuery("SELECT * from Login");
rs.last();
System.out.println(rs.getInt("username"));
id = rs.getInt("username");
rs.close();
} finally{
try{
conn.close();
}catch(SQLException e){
System.out.println(e);
}
}
return id;
}
The part of the method which calls the createNewLoginUsers method
if(newPasstxtfld.getText().equals(retypeNewPasstxtfld.getText())){
//update into database
try {
int username = CreateUsersDAO.createNewLoginUsers( (String) newUserRoleBox.getSelectionModel().getSelectedItem(), newPasstxtfld.getText());
Alert confirmation = new Alert(Alert.AlertType.INFORMATION);
confirmation.setHeaderText("New User Details has been created. Your username is " + username);
confirmation.showAndWait();
} catch (SQLException e) {
}
EDIT:
Databases table added and it's in the provided link below
https://imgur.com/a/Dggp2kc and edit to the codes instead of 2 try blocks in one method i have placed it into a different similar method, updated my codes to the current one I have.
I am using Mysql netbeans . I have created a db table "userdetails_summertrainingproject" . In the login form I have two fileds to fill one is "UUId_JTextField" and other is "Password1_JPasswordField". I want to compare that the password value entered by the user is same as that in db for the particular UUId entered by the user. UUid is unique.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = new String(password1);
if(rs.getString(query)==pass1){
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
}
catch(Exception e){
System.out.println("Exception in Login:"+e.getMessage());
}
Above is the code I am using.
The Exception is:
Exception in Login:Column 'SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;' not found.
Try this code, you missed rs.next()
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
String query = "SELECT password FROM userdetails_summertrainingproject WHERE UUId=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, UUId_JTextField.getText());
ResultSet rs = preparedStatement.executeQuery();
char[] password1 = Password1_JPasswordField.getPassword();
String pass1 = Arrays.toString(password1);
rs.next();
if (rs.getString("password").equals(pass1)) {
JOptionPane.showMessageDialog(null, "Logged in successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
I think it is batter to use another method for get connection string. otherwise you have to write bellow code again and again.
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/mysql", "root", "");
EDIT:
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
String query = "SELECT UUId FROM userdetails_summertrainingproject;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
rs.next();
String UUId = rs.getString("UUId");
System.out.println("UUId " + UUId);
} catch (Exception e) {
e.printStackTrace();
}
}
Create a class and add this code. then check this code is working or not.
please make sure port, database name, user and password is correct.
If this is give com.mysql.jdbc.CommunicationsException: Communications link failure. most probably your port is incorrect.
I am use these two libraries.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query="SELECT password FROM tryingtable WHERE name=?;";
PreparedStatement prepstmt=conn.prepareStatement(query);
prepstmt.setString(1,jtf.getText());
ResultSet rs=prepstmt.executeQuery();
rs.next();
String result=rs.getString("password");;
char[] pass = jpf.getPassword();
String password1= new String(pass);
if(result.equals(password1))
JOptionPane.showMessageDialog(null, "go!!");
else
JOptionPane.showMessageDialog(null, "no!!");
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
e.getStackTrace();
}
when you want to compare password field to textfield use
char[] pass_char = passwordField.getPassword();
String pass_string = new String(pass_char);
Above code will give you your password field value in string form, then
if(pass_string.equals(textfield))
JOptionPane.showMessageDialog("Password match");
else
JOptionPane.showMessageDialog("Password did not match");
I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.
For example:
If TextField1 == to the data in the database.
Output: Swept by GSW.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list WHERE id = ?";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
}
}
}catch(SQLException exc){
System.out.println("Not Found!");
}
Kindly Check the Image Output.
I attached the image file below.
Sample Output
Here are some mistake I see
You use a parameter in the query, "SELECT * FROM item_list WHERE id = ?";so use a PreparedStatement
Set the parameter to that PreparedStatement ps = connection.preparedStatement(query); with ps.setInt(1, Integer.parseInt(TF[0].getText()));
Don't catch the exception without logging it, here your query as a syntax error but you don't know it.
careful with uppercase in the database field name "Id"
This might not be everything ...
And of course, now that you get only the row with that ID, you can simply check if there is at least one row return to validate that it exists.
First of all, you need to log a stack trace of an exception that is thrown. At least you can use exc.printStackTrace() in your catch section.
Second, your issue is that you declared a parameter for your SQL query, but you have not put any value to it.
PreparedStatement p = con.prepareStatement("SELECT * FROM item_list WHERE id = ?");
p.setString(1, TF[0].getText() ); //VALUE_FROM_YOUR_TEXT_INPUT
You don't need to iterate over all result set to check if a user with such id exists. You can just check that result set is not empty.
you can use intValue() for Integer object obvious if your object is not null
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()).intValue() == id){
System.out.println(id);
}
}
You're not setting the value of the id parameter in the statement. Not familiar with Java but in C# it would be something like
statement.Parameters.AddWithValue("#id", id)
Thank You guys! I've been trying and reading all your suggestions, and I've found and debugged it. Thanks to the one said that I need to check what message I can get in the catch.
Appreciated all your help.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
JOptionPane.showMessageDialog(null, "FOUND!");
}
else{
JOptionPane.showMessageDialog(null, "Not Found!");
}
}
}catch(SQLException exc){
JOptionPane.showMessageDialog(null, exc.getMessage());
}
ID Found!
code in update button
String password = new String(oldPass.getPassword());
String newPassword = new String(newPass.getPassword());
String realpass = zz.getText();
String us = z.getText();
if(password.equals(realpass))
{
System.out.println("ok");
String query = "UPDATE user SET password = '"+newPassword+"' WHERE username = '"+us+"'";
try{
Statement st = (Statement) con.prepareStatement(query);
int i = st.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null, "Ooopps! I guess you should call your programmer. ^^");
}
}catch(Exception e){
System.out.println(e);
}
}
code in log in
Methods m = new Methods();
String pass = new String (password.getPassword());
String user = username.getText();
if(m.logInUser(user, pass)==true){
form2 f = new form2();
f.setUser(user);
f.setPass(pass);
f.setVisible(true);
this.dispose();
}....and so on....
code for method log in user
public boolean logInUser(String user, String pass){ //true = nakarecord na sa database login form
try{
String query = "Select * from user where username = ? && password = aes_encrypt('"+pass+"', 'nicanor')";
PreparedStatement pst = (PreparedStatement) con.prepareStatement(query);
pst.setString(1,user);
ResultSet rs = pst.executeQuery();
if(rs.next()){
return true;
}
else{
return false;
}
}
catch(Exception e){
System.out.println(e);
return false;
}
}//logInUser
it says successfully connected in sql and the database is updated but i cant see the next form that should pop up after i entered the updated password
There are few problems with your code:
(1) In your update() logic, you are using the mix of PreparedStatement and Statement together, rather use always use PreparedStatement to bind the input parameters, otherwise they (statements/queries) are prone to SQL injection attacks.
You can refer the below code with inline comments to bind the input parameters with PreparedStatement:
//Write the SQL query with ? to bind the parameters in PreparedStatement
String query = "UPDATE user SET password = ? WHERE username = ?";
PreparedStatement pstmt = null;
try{
//create the PreparedStatement object
pstmt = con.prepareStatement(query);
//bind the input parameters using setString()
pstmt.setString(1, newPassword);
pstmt.setString(2, us);
//execute the prepare statement now
int i = pstmt.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password
is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null,
"Ooopps! I guess you should call your programmer. ^^");
}
} catch(Exception e){
System.out.println(e);
} finally {
if(pstmt != null)
pstmt.close();
if(con != null)
con.close();
}
Also, remember that database resources are costly and you need to close the resources in the finally block as shown above, otherwise you will end up with resource leaks.
(2) In your logInUser() logic, you are using && which is incorrect, rather in sql you need to use AND operator as shown below:
String query = "Select * from user where username = ?
AND password = aes_encrypt('"+pass+"', 'nicanor')";
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