I am working on a project to create a login page. To do this I am using a database to store the user information. As of right now there are four columns in my database: username, password, email, and admin.
Right now I am having a problem accessing that database using a prepared statement/Result set format. Right now I get to the third return, print out the imputed username and password then generate an error. Am I formatting my prepared statement incorrectly?
Okay, based of previous answers I have corrected most of my code(thank you) and now I have this error when I am trying to print out of the result set:
java.sql.SQLException: Column Index out of range, 2 > 1.
any ideas?
My code:
Properties props = new Properties();
props.setProperty("user", "root");
props.setProperty("password", "root");
props.setProperty("databaseName", "dbname");
String ret = ERROR;
Connection myCon = null;
try{
System.out.println("got here 1!");
Class.forName ("com.mysql.jdbc.Driver").newInstance();
System.out.println("got here 2!");
myCon = DriverManager.getConnection("jdbc:mysql://ipaddresshere:3306/dbname",props);
System.out.println("got here 3!");
System.out.println(username);
System.out.println(password);
String dbQuery = "SELECT count(*) FROM loginTestTable where username = "+username+" AND password = "+password+"";
//PreparedStatement prep = myCon.prepareStatement(dbQuery);"
PreparedStatement ps = myCon.prepareStatement(dbQuery);
ps.setString(1, username);
ps.setString(2, password);
ResultSet result = ps.executeQuery();
System.out.println("got here 4!");
while (result.next()) {
System.out.println("got here 5!");
ret = SUCCESS;
System.out.println("username: "+result.getString(1)+" password: "+result.getString(2)+" email: "+result.getString(3));
if(result.getString(4).toLowerCase()=="YES"){
ret = "admin";
}
}
}catch(Exception e){
System.out.println("arg there be an error me matey!");
ret = ERROR;
}finally{
if(myCon!=null){
try{
myCon.close();
}catch (Exception e){
}
}
}
return ret;
There are multiple problems with your code:
First, you're missing quotes around username and password.
String dbQuery = "SELECT count(*) FROM loginTestTable " +
"where username = '"+username+"' AND password = '"+password+"'";
Second, the PreparedStatement#setString() methods have no effect unless you define your query with place holders ? like
String dbQuery = "SELECT count(*) FROM loginTestTable " +
"where username = ? AND password = ?";
Third, you must never compare strings with equality == operator. Use String.equals() as
// also note you need toUpperCase() here
"YES".equals(result.getString(4).toUpperCase());
Change the line:
String dbQuery = "SELECT count(*) FROM loginTestTable where username = "+username+" AND password = "+password+"";
By:
String dbQuery = "SELECT count(*) FROM loginTestTable where username = ? AND password = ?";
Related
Trying to use JDBC to handle some logic for validating if a user and password are in the DB and correct.
The method should return true if they are in the DB or false if not
I've tried changing the methods and it always either lets any user in, even if they dont exist, or no one in, even if they are in the DB.
Can someone explain how to fix this, funnily enough it was working the other day but I've changed something and unsure what...
JDBC code
public boolean checkUser(String username, String pass) {
boolean valid = false;
try {
//loading drivers for mysql
Class.forName("org.apache.derby.jdbc.ClientDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/workoutDB", "root", "root");
System.out.println("username = " + username);
System.out.println("pass = " + pass);
String sql = "SELECT * FROM users WHERE (username = '" + username + "' AND password = '" + pass + "')";
System.out.println("lo " + sql);
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(sql);
out.println(valid);
if(rs.next()) {
valid = true;
out.println(valid);
} else {
valid = false;
}
} catch (ClassNotFoundException | SQLException e) {
out.println(e);
}
out.println(valid);
return valid;
}
I've included an image of the console output, the username test, with password tes is in the db.
Sorry it was another class which does the same thing I added the prepared too, it also always returns true or false regardless of if the condition is met.
public boolean checkUser(String username, String pass) {
boolean valid = true;
try {
//loading drivers for mysql
Class.forName("org.apache.derby.jdbc.ClientDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/workoutDB", "root", "root");
System.out.println("username = " + username);
System.out.println("pass = " + pass);
//String sql = "SELECT username FROM users WHERE (username = '" + username + "')";
//String sql2 = "SELECT password FROM users WHERE (password = '" + pass + "')";
//System.out.println(sql);
//System.out.println(sql2);
//Statement statement = con.createStatement();
//ResultSet rs = statement.executeQuery(sql);
//ResultSet rs2 = statement.executeQuery(sql2);
PreparedStatement ps = con.prepareStatement("select * from users where username=? and password=?");
ps.setString(1, username);
out.println("ps "+ps);
ps.setString(2, pass);
out.println("ps "+ps);
ResultSet rs = ps.executeQuery();
valid = !rs.next();
} catch (ClassNotFoundException | SQLException e) {
out.println(e);
}
out.println(valid);
return valid;
}
I am new in java there is a piece of code which is written in if-else i want to change this to switch statement but i have no idea to write in switch statement.Here is my code.
<%
String userid = request.getParameter("username");
String pwd = request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/auto_lube","root", "password");
Statement st = con.createStatement();
ResultSet rs; `rs = st.executeQuery("select * from users where uname='" + userid + "' and pass='" + pwd + "' and role='users'");`
if (rs.next()) {
String username = rs.getString("uname");
String email = rs.getString("email");
session.setAttribute("customer_name", username);
int user = rs.getInt("id");
session.setAttribute("customer_id", user);
if(dat.after(date)){
MailClient client = new MailClient();
String from="username#gmail.com";
String to = email;
String subject="Please Attention";
String message="Please change your vehicles oil today is expiery date?";
client.sendMail(from,to,subject,message);}
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("index.jsp");
} else {
response.sendRedirect("invalid.jsp");
}
The real question here is - how can my code divert to the invalid page when the query returns no results.
You should look at this - https://stackoverflow.com/a/6813771/1355930 - which shows a better way of working with result set. Your code should read something like:
if (rs.isBeforefirst()) {
// do the stuff for logged in user
response.sendRedirect("index.jsp");
} else {
response.sendRedirect("invalid.jsp");
}
My guess, though, is that the problem isn't your if statement. Try redirecting to the invalid.jsp in all cases to make sure that you can actually do that redirect.
public int addUsers(int USER_ID,String FIRST_NAME,String LAST_NAME,String PASSWORD,String USERNAME,String USER_PERMISSION) throws SQLException {
Connection conn = null;
conn = getConnectivity(conn) ;
getConnectivity(conn);
String sqlSelect = "SELECT * from USER_DETAILS";
PreparedStatement pres = conn.prepareStatement(sqlSelect);
ResultSet rs1 = pres.executeQuery();
if(rs1.next()){
String Username = rs1.getString(5);
System.out.println("username found "+Username);
System.out.println("username input " + USERNAME);
System.out.println("password input " + PASSWORD);
if (Username.equals(USERNAME)){
System.out.println("Username already exists");
conn.close();
}
else{
System.out.println("FOUND ELSE");
String sql = "INSERT INTO USER_DETAILS VALUES (?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, USER_ID);
ps.setString(2, FIRST_NAME);
ps.setString(3,LAST_NAME);
ps.setString(4,PASSWORD);
ps.setString(5,USERNAME);
ps.setString(6,USER_PERMISSION);
int result = ps.executeUpdate();
System.out.println(result);
}
}
conn.close();
return USER_ID;
}
and for login I am using
public boolean login(String USERNAME, String PASSWORD) throws SQLException
{
boolean result = false;
Connection conn = null;
conn = getConnectivity(conn) ;
String sqlSelect = "SELECT * from USER_DETAILS";
PreparedStatement pres = conn.prepareStatement(sqlSelect);
ResultSet rs1 = pres.executeQuery();
if(rs1.next()){
String Username = rs1.getString(5);
String Password = rs1.getString(4);
String UserPermission = rs1.getString(6);
System.out.println("username found "+Username);
System.out.println("username input " + USERNAME);
System.out.println("password input " + PASSWORD);
if (Username.equalsIgnoreCase(USERNAME) && Password.equalsIgnoreCase(PASSWORD) && UserPermission.equalsIgnoreCase("blocked")){
System.out.println("User Logged in");
conn.close();
}
System.out.println("gets out of the code");
}
conn.close();
return result;
}
first of all it is allowing to enter more than one entry, so duplicates occurring regardless of my if statement, and when i add fresh new data and try to see I can log in, it still compares with previously added data and does not work. Can someone see what am i doing wrong here. please thanks
below is the system print out i get ,
Connection Valid
username found kamran (don't know why he is still picking up this column)
username input macbook (these i have already in my database)
password input hello (these i have already in my database)
gets out of the code
Connection Valid
Connection Valid
username found kamran (don't know why he is still picking up this column)
username input macho (these i have already in my database)
password input hello (these i have already in my database)
FOUND ELSE (dont know why it adds data when they already exist in database)
1
Your code doesn't make sense: you are querying for all users and only checking the first returned user if it matches. Of course that is going to fail if the first returned user doesn't match: in addUsers you will try to add the user if the first user returned doesn't match, in login a user can only login if it is the first user.
You need to use a WHERE clause to only request the user you want to check:
// Note: this assumes a case insensitive collation
String sqlSelect = "SELECT * from USER_DETAILS WHERE username = ?";
try (PreparedStatement pres = conn.prepareStatement(sqlSelect)) {
pres.setString(1, USERNAME);
try (ResultSet rs1 = pres.executeQuery()) {
if (!rs1.next) {
// user doesn't exist yet, create...
}
}
}
You need to do something similar for login (but then with if (rs1.next()) instead).
There are more problems with your current code: you are storing plaintext passwords: you should really hash them with a strong password hash like PBKDF2. Also please follow the java naming conventions. Variables and parameters are camelcase so not USERNAME but username (or userName), not UserPermission, but userPermission. This improves the readability for people who are used to the java naming conventions.
Hey guys I have a weird problem , if I enter my correct credentials from my database I GET AN ERROR, if I enter the wrong credentials everything is okay.
Exception in thread "main" java.sql.SQLException: Column 'username' not found.
This error occurs when I enter the correct credentials
Also I have another problem, my passwords are encrypted with MD5 and I have no idea how to write that into my SELECT , tried this but without any success.
resultSet = statement.executeQuery("SELECT password FROM cards.username WHERE username = '" + username + "' && password = 'MD5(" + password + ")'");
So this is my class
public void readDataBase() throws Exception {
//Scanners
Scanner in = new Scanner(System.in);
System.out.print("Username: ");
String username = in.nextLine();
System.out.print("Password: ");
String password = in.nextLine();
System.out.println(" ");
//---------------------
String databaseUsername = "";
String databasePassword = "";
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/cards?"
+ "user=root&password=password");
// statements allow to issue SQL queries to the database
statement = connect.createStatement();
resultSet = statement.executeQuery("SELECT password FROM cards.username WHERE username = '" + username + "' && password = '" + password + "'");
//writeResultSet(resultSet);
while (resultSet.next()) {
databaseUsername = resultSet.getString("username");
databasePassword = resultSet.getString("password");
}
if (username.equals(databaseUsername) && password.equals(databasePassword))
System.out.println("Success !! ");
else
System.out.println(" Failure ");
//---
//--------------------------------------------------------------------------------------------------
// resultSet gets the result of the SQL query
// resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
//
// writeResultSet(resultSet);
//
// // preparedStatements can use variables and are more efficient
// preparedStatement = connect
// .prepareStatement("insert into FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// parameters start with 1
// preparedStatement.setString(1, "Test");
// preparedStatement.setString(2, "TestEmail");
// preparedStatement.setString(3, "TestWebpage");
// preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
// preparedStatement.setString(5, "TestSummary");
// preparedStatement.setString(6, "TestComment");
// preparedStatement.executeUpdate();
// preparedStatement = connect
// .prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// resultSet = preparedStatement.executeQuery();
// writeResultSet(resultSet);
//
// // remove again the insert comment
// preparedStatement = connect
// .prepareStatement("delete from FEEDBACK.COMMENTS where myuser= ? ; ");
// preparedStatement.setString(1, "Test");
// preparedStatement.executeUpdate();
//
// resultSet = statement
// .executeQuery("select * from FEEDBACK.COMMENTS");
// writeMetaData(resultSet);
//
//---------------------------------------------------------------------------------------------------------
} catch (Exception e) {
throw e;
} finally {
close();
}
}
And this is another class where I call this method
package mysqltryouts;
import java.util.Scanner;
import mysqltryouts.MySQLtryouts;
public class main {
public static void main(String[] args) throws Exception {
MySQLtryouts dao = new MySQLtryouts();
dao.readDataBase();
}
}
This is my simple DB with only 1 table :
I am kinda new with this mySQL and Java stuff, any help would be really appreciated
*EDIT #1
Fixed the main problem, but I still don't know how to make the MD5 thing, I mean when I enter my password in java, it gets itself crypted, I've used this method in VB.NET and tried an equivalent but with no success. :
Dim SqlQuery As String = "SELECT COUNT(*) From users1 WHERE username = #Username AND password = MD5(#Password); "
My java attempt:
resultSet = statement.executeQuery("SELECT * FROM cards.username WHERE username = '" + username + "' AND password = ('MD5(" + password + ")'");
my password field is varchar(10) and I just add MD5 when I manually add the data from phpmyadmin or from my app
While retrieving from the table too, apply MD5 on your password input value to compare with database field value.
SQL statement:
select count(*) > 0 as match_found
from table_name
where username = ?
and password = md5( ? )
In JAVA:
Use PreparedStatement for value binding with the statement.
PreparedStatement pst = con.prepareStatement( sqlQuery );
pst.setString( 1, userName );
pst.setString( 2, password );
ResultSet rs = pst.executeQuery();
boolean loginSuccess = false;
if( rs.next() ) {
loginSuccess = rs.getBoolean( "match_found" );
}
I am building a simple security system using java (eclipse) and I am using the MYSQL statement to pull data from the database
ResultSet rs = statement.executeQuery("select name, username, password from securitysystem.employee where username = '" + username + "' and password = '" + password + "'");
but what if i wanted to create a variable user= name, how would I do that? name is referring to the name retrieved using the statement above.
Firstly, you should never put your parameter right into a query string.
Instead, do this:
PreparedStatement ps = connection.prepareStatement("select name, username, password "+
"from securitysystem.employee where username = ? and password = ?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
To get the results, do this:
if (rs.next()) { //move to 1st result row
String name = rs.getString(1); //first result column
String user = rs.getString(2); //second result column
// ..etc
}
How about:
while(rs.next()) {
String user = rs.getString("name");
}