I try duplicate the entries in the username column but the result is always in the else statement which is the data is successfully inserted into the table which should not be duplicated based on the if statement. By the way String value1=username1.getText();.
here's the code:
String sq = "SELECT username FROM login where username = '"+value1+"'";
if (sq.equals(value1)){
JOptionPane.showMessageDialog(null,"username is already existed! please
create new username.");
}
else{
int k=st.executeUpdate("insert into
login(username,password,firstname,lastname,address,contactno)
values('"+value1+"','"+value2+"','"+value3+"','"+value4+"',
'"+value5+"','"+value6+"')");
JOptionPane.showMessageDialog(null,"Data is successfully saved");
}
You just create the SQL string and never run it (instead, you compare it to the username, which will always be false).
You should actually execute it and check the result.
E.g. (error handling and resource cleanup omitted for brevity's sake):
Connection conn = // Connect to the database...
PreparedStatement ps =
conn.prepareStatement("SELECT username FROM login where username = ?";
ps.setString(1, value1);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog
(null,"username is already existed! please create new username.");
}
sq will never be equal to value1 if you just assign it to a complete SELECT statement:
String sq = "SELECT username FROM login where username = '"+value1+"'";
What you are missing is the DB request for your sq String.
sq contains the query (sql code)
String sq = "SELECT username FROM login where username = '"+value1+"'";
value1 contains the username value (for example "user1"). So
sq.equals(value1)
will be always false
"SELECT username FROM login where username = '"+value1+"'" != value1
String Basics:
String sq = "Something in double quotes"
Assigns Something to sq.
And
String value1=username1.getText();
May get some other string, lets say for example "root"
sq.equals(value1)
Now String class equals() method check content of both Strings(sq and value1).
And if not equal returns false, which happens in your case.
Now how to achieve your goal? people already answered that check it.
I recommend to study yourself
Related
Im trying to get information in sql from database, there are two entries in each column but and with the following code, i am able to get the first entry information, if i wanted to get the second entry's records and display it also in project how would i get it?
String username1= rs.getString ("USERNAME");
String password1= rs.getString ("PASSWORD");
String aname1= rs.getString ("a_name");
String aname2= rs.getString ("a_name");
System.out.print("Enter Your Username: ");
String usernamea=(br.readLine());
System.out.print("Enter Your Password: ");
String passworda=(br.readLine());
if ((usernamea.equals(username1) && (passworda.equals(password1))))
{
System.out.println("Login Success! Welcome "+aname1+"!");
System.out.println("You are granted with Admin Acess!");
rs.close();
}
else if ((usernamea.equals(username2) && (passworda.equals(password2))))
{
System.out.println("Login Success! Welcome Guest User!");
rs.close();
}
I'm not quite sure what you are asking, nor am I sure how the code you posted actually relates to what you are asking.
When you say "you want the 2nd entry", I am assuming you mean the 2nd record in the SQL table.
try(Connection conn = DriverManager.getConnection(url, username, password)){
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
rs.next();
//All data stored in the ResultSet obj, to which you may loop through & select rows of interest. Particularly useful methods are .getMetaData(), .getRow(), etc.
}
Hopefully this is what you are asking for.
If you already have a ResultSet rs, you can call rs.next(). For Example some Code:
if (rs.next())
{
s.name = rs.getString(1);
s.creator = rs.getString(2);
s.dbname = rs.getString(3);
s.tsname = rs.getString(4);
s.cardf = rs.getFloat(5);
s.npages = rs.getInt(6);
s.statstime = rs.getString(7);
s.avgrowlen = rs.getInt(8);
}
Considering your code:
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
String username1 = rs.getString ("USERNAME");
String password1 = rs.getString ("PASSWORD");
String aname1 = rs.getString ("a_name");
rs.next();
String username2 = rs.getString ("USERNAME");
String password2 = rs.getString ("PASSWORD");
String aname2 = rs.getString ("a_name");
Now you can check both the first entry and the second.
Nevertheless, the better practice is to create a user object, save username, password and aname in it.
Then, using some loop, you can go through the entire result set and get all the information from it.
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
List<User> userList = new ArrayList<User>();
while(rs.next()) {
User user = new User();
user.setUsername(rs.getString ("USERNAME"));
user.setPassword(rs.getString ("PASSWORD"));
user.setAname(rs.getString ("a_name"));
userList.add(user);
}
i've been trying to make this piece of code work work for a while now but seems like it wont. My User inputs Username and Password and then the program compares it to the DB. However it displays Invalid Credentials even though when i output the password it displays the exact same i've input.Just a few points, i know some of you are going to point on things like Using a seperate class for Connection, Check against username for password instead of using Select *, use hashings and all. But right now at the moment i just need to get this code work. Only after that i will be able to work on other aspects to ENHANCE its efficiency. Thank you all in advance.:)
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
Username1 = "jTextField1.getText()";
Password1 = "jPassword1Field2.geText()";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/";
String dbName = "VideoSystem" ;
String userName = "root";
String passWord = "**mypassword**";
Connection conn = DriverManager.getConnection(url+dbName, userName, passWord);
Statement st = conn.createStatement();
String sql = ("SELECT * FROM Identification");
ResultSet rs = st.executeQuery(sql);
while(rs.next())
{
password = rs.getString("Password");
if( Password1.equals(password))
{
MenuSelection obj1 = new MenuSelection();
obj1.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "Invalid Credentials", "System Message", JOptionPane.INFORMATION_MESSAGE);
}
}
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
Those two lines:
Username1 = "jTextField1.getText()";
Password1 = "jPassword1Field2.geText()";
They are string literals, so unless your password is literally jPassword1Field2.geText(), there's not gonna be a match. I think you meant:
Username1 = jTextField1.getText();
Password1 = jPassword1Field2.getText();
Note however, that JPasswordField.getText() is deprecated since Java 2. You should use getPassword() instead:
Password1 = new String(jPassword1Field2.getPassword());
The documentation justifies the deprecation of getText() with "security reasons" that I can't claim to understand, but you still shouldn't use deprecated parts of the API.
And I know you some of the below already and none of that is part of your question, but I really suggest that you
Check against the username. It should be obvious why.
Hash passwords. Always.
Only fetch what you need, mostly for performance reasons. Usually the best way is to use a WHERE clause in SQL (that brings the need to sanitize your input, but you should do that anyway) and building a list of columns instead of fetching *.
Use backticks for database/table/column names in SQL to avoid things like accidentally using a keyword as table/column name or so.
Applying the above, I suggest the following query (assuming the name field is called Username):
PreparedStatement st = conn.prepareStatement("SELECT `Password` FROM `Identification` WHERE `Username` = ?");
st.setString(1, Username1);
ResultSet rs = st.executeQuery();
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.
How do I validate a certain email and password while an user logs in?
protected void doPost(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException {
String email=request.getParameter("email");
String pass=request.getParameter("pass");
OutputStream out = res.getOutputStream();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/college", "root", "root");
Statement st=con.createStatement();
String strSQL = "SELECT email,password FROM student";
How do I continue after the SELECT statement? I would prefer using the if...else statement to do the validation.
First close all connection resources properly - use a Java 7 try-with-resources.
Here is an simple example:
final String email = request.getParameter("email");
final String pass = request.getParameter("pass");
try (final Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/student", "root", "root");
final PreparedStatement statement = con.prepareStatement("SELECT COUNT(*) AS count FROM student WHERE email=? AND password=?");) {
statement.setString(1, email);
statement.setString(2, pass);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
final int rows = resultSet.getInt("count");
if (rows > 1) {
throw new IllegalStateException("More than one row returned!");
}
boolean validUser = rows == 1;
}
}
}
But really you should hash passwords in the database. Use something like jBcrypt. Your code would then look like:
final String email = request.getParameter("email");
final String pass = request.getParameter("pass");
try (final Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/student", "root", "root");
final PreparedStatement statement = con.prepareStatement("SELECT pass FROM student WHERE email=?");) {
statement.setString(1, email);
statement.setString(2, pass);
try (final ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
final String hash = resultSet.getString("pass");
final boolean valid = BCrypt.checkpw(pass, hash);
}
}
}
Obviously you need to add error checking if there are no rows returned from the query. You also need to check that only one row is returned. But I leave that as an exercise.
you can use if, if you like. Use the input as your where statement and then check to see if there is a match, error or null, then execute whatever you want it to do.
You can use email and password in the SQL statement itself. like:
SELECT email, password from student where email = ? and password = ?
prepare above statement and bind the parameters.
This way validation will be done on the DB and you just need to check the result count (which has to be 1). You should have index on email column to have better SQL performance.
Do you relay need to fetch all students?
PreparedStatement st = con.prepareStatement("SELECT count(*) FROM student WHERE email=? AND password=?");
st.setString(1, email);
st.setString(2, pass);
ResultSet rs = st.executeQuery();
rs.next();
int count = rs.getInt(1);
if (count == 1) {
// password and email are correct
}
For this answer, I'll assume that by "validate email and password", what you mean is you want to authenticate the user based on their email address and a password. And not that you want to check whether the email address is a real email address.
So, the first thing you need to do is encrypt the passwords in your database, using a hash algorithm and a random salt. You record the salt alongside the hashed password.
Next thing is, when the user logs in, you look up the salt for that user, and you perform the same hash with the salt. Then you compare the result of that with the previously saved password hash, and if they're the same, then the passwords were the same.
It's important that the salt be random and different for every user.
Plenty of reading to be found on the above terms on the Internets.
Once you've done that, you should also apply the very sensible suggestions in other answers to only select the user you want, and handle your resources correctly.
WARNING I am not an expert on security, and neither are you. If you're implementing a log-in system for an exercise, fine. If it's for the real world, use something that's been written by someone who knows what they're doing.
I inserted one column in sql with null value from java.while retrieving back it is not working with null.i also checked with string.length().But when i printed the value in System.out. the value is showing as null (just null).when i checked it with condition it is not entering into loop.
String id ="1234";
String name="pratap";
String gender=null;
String email=null;
String service="GOOGLE";
log.info(id+name+gender+email) //output is 1234pratapnullnull
String insert = "INSERT INTO oauthuser VALUES('"+id+"','"+name+"','"+gender+"','"+email+"','"+service"')";
In the retrieval
query ="Select * FROM oauthuser where id="+"'"+id+"'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
id=rs.getString(1);
name=rs.getString(2);
gender=rs.getString(3);
email=rs.getString(4);
service_provider_name=rs.getString(5);
System.out.println(gender+email+name);//output is nullnullpratap
}
if(gender!="male" && gender!="female")
System.out.println("it is printing");
if(gender==null)
System.out.println("it is not printing");
con.close();
From your somewhat cryptic description of the problem I suspect that you may have inserted the string "null" rather than the SQL NULL value. The two are not the same (very different, in fact).
edit Having reviewed the code, this is exactly what happens. Take, for example, gender:
String gender = null;
...'"+gender+"',...
The above converts it to 'null' (i.e. the SQL string "null"), and inserts that into the database.
My basic advice would be to read up on PreparedStatement and use that instead of building the SQL query bit by bit as you're doing right now.
Finally, the following is broken:
if(gender!="male" && gender!="female")
This should be
if(!gender.equals("male") && !gender.equals("female"))
you can try "null" instead of NULL , but better to show us the code
after your update
remove + sign from your query like this
String id ="1234";
String name="pratap";
String gender="null";
String email="null";
String service="GOOGLE";
log.info(id+name+gender+email) //output is 1234pratapnullnull
String insert = "INSERT INTO oauthuser VALUES('"id"','"name"','"gender"','"email"','"service"')"
and when you select , modify like this
if(gender.equals("null"))
System.out.println("it is not printing");
Maybe your value is not null but "null" string? Start your application in debug, put break point and check it.