SQLite Log-In Check username & password - java

I am creating an Application (Using Java & SQLite)(JFrame, using Netbeans) I have users who I want to log in. (I have all the correct packages JDBC, SQLite etc)
The issue I am having seems to be getting the username/password to check against my users.db file.. I am using Java and SQLite. I'm using JDBC also.
Some of my code as an example (This sends my users information to make the account, Works fine), my database is users.db and I want to compare username/password against USERNAME & PASSWORD
Connection dbconn = null;
Statement stmt = null;
String query = "insert into USERS(ID, FIRSTNAME, SECONDNAME, USERNAME, PASSWORD, JAVALESSON, CLESSON, PYTHONLESSON) values(?, ?, ?, ?, ?, ?, ?, ?)";
try {
Class.forName("org.sqlite.JDBC");
dbconn = DriverManager.getConnection("jdbc:sqlite:users.db");
Statement statement = dbconn.createStatement();
PreparedStatement pstmt = dbconn.prepareStatement(query);
I have a UsernameLoginBox & PasswordLoginBox, How would I check USERNAME & PASSWORD (From SQLite Database) against the string in the textbox's for log in?
TRIED CODE:
Connection conn = null;
ResultSet rs =null;
PreparedStatement pst =null;
String sql1 = "Select * from USERS where USERNAME=? and PASSWORD=?";
try{
pst = conn.prepareStatement(sql1);
pst.setString(1, UsernameLogIn.toString());
pst.setString(2, PasswordLogInField.getText());
rs=pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username & Password are correct");
} else {
JOptionPane.showMessageDialog(null, "Username & Password are incorrect");
System.out.println("Logged in");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
System.out.println("Not Logged in");
}
And this:
Connection cbconn = null;
Statement stmt2 = null;
String upcheck = "SELECT USERNAME, PASSWORD FROM USERS";
ResultSet rs = Statement.executeQuery(upcheck);
while (results.next()) {
String staffname = results.getString("snameeee");
String password = results.getString("SPwd");
if ((f.equals(staffname)) && (s.equals(password))) {
JOptionPane.showMessageDialog(null, "Username and Password exist");
}else {
//JOptionPane.showMessageDialog(null, "Please Check Username and Password ");
}
results.close();
} catch (SQLException sql) {
out.println(sql);

I guess the query should be :
Select PASSWORD from USERS where USERNAME = 'theNameInTextBox';

Related

How this code checks equality of the password and the username That stored in database?

this a login button code in java in NetBeans.
Is there another way to check the equality in database?
what is the while (Rs. Next) do?
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String sql = "select username,password from user Where (username =? and password =? )";
try {
int count = 0;
pst = conn.prepareStatement(sql);
pst.setString(1, txt_username.getText());
pst.setString(2, txt_password.getText());
rs = pst.executeQuery();
{
}
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Sucess");
MainMenu j = new MainMenu();
j.setVisible(true);
this.dispose();
} else {
JOptionPane.showMessageDialog(null, "Username and Password is not correct");
#
Maybe this helps:
https://1bestcsharp.blogspot.com/2016/08/java-login-form.html
Briefly, if you query a DB with two parameters: username and password and recieve a not empty response - that means the pair username and password is valid.
Another way is needed when you store password in the DB not as a plain text. You can query a password if you store crypted passwords in DB. See the answer to that question Verify BCrypt Hash password when Login

Java Mysql Prepared statement syntax issue

I am getting a syntax error with the SQL code within a prepared statement. I have read the other answers on the site and I cannot work out the issue. My code is as follows
private boolean validate_login(String username,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
String url = "jdbc:mysql://localhost/db_webstore";
String user = "root";
String pw = "Password";
String SQL = "select * from tbl-users where Tbl-UsersUserName=? and Tbl-UsersPassword=?";
Connection conn = DriverManager.getConnection(url, user, pw);
PreparedStatement pst;
pst = conn.prepareStatement(SQL);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
The error message is as follows
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-users where Tbl-UsersYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-users where Tbl-Users
Can anyone offer some advice? Thanks in Advance
You are probably missing some dots in your query. Table and column name need to be separated by a dot. Furthermore the table name needs to be quoted as - is not allowed in unquoted identifiers (see here):
String SQL = "select * from `Tbl-Users`"
+ " where `Tbl-Users`.UserName=?"
+ " and `Tbl-Users`.Password=?";
UPDATE:
Added link to MySQL docu on valid identifiers
Quoted table name using `
you should include the port number(which is 3306 for MySQL) in your database connection
accordingly your code should be corrected as follows
private boolean validate_login(String username,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
String url = "jdbc:mysql://localhost:3306/db_webstore";
String user = "root";
String pw = "Password";
String SQL = "select * from tbl-users where Tbl-UsersUserName=? and Tbl-UsersPassword=?";
Connection conn = DriverManager.getConnection(url, user, pw);
PreparedStatement pst;
pst = conn.prepareStatement(SQL);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}

Having great difficulty implementing login system using SQLite in Java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String query;
boolean login = false;
String username = jTextField1.getText();
String password = jTextField2.getText();
try{
query = "SELECT (cUsername AND cPassword) FROM Customer WHERE cUsername = '"+username+"' AND cPassword = '"+password+"'";
pst = conn.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.executeQuery();
String userCheck = rs.getString(1);
String passCheck = rs.getString(2);
if((userCheck.equals(username)) && (passCheck.equals(password)))
{
login = true;
System.out.println("It actually works?!");
}
else
{
login = false;
System.out.println("Psyche, that's the wrong number!");
}
}
catch(Exception e){
System.out.println(e);
}
System.exit(0);
}
I'm currently having difficulty implementing a login system in my code. I'm trying to retrieve the text from username and password jTextFields and then query them to the database but it's not working. At the moment I'm getting
java.lang.ArrayIndexOutOfBoundsException: 0
and I unfortunately have no idea why. Any help would be GREATLY appreciated.
Your query and the logic behind got a lot of work to do:
First of all, if you want a parametrised query, you must use '?' instead of the value. Then the pst.setString will work.
Secondly, you must affect the pst.executeQuery(); to a ResultSet
query = "SELECT cUsername, cPassword FROM Customer WHERE cUsername = ? AND cPassword = ?";
pst = conn.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
String userCheck = rs.getString(1);
String passCheck = rs.getString(2);
}

How do I verify password entered is the password associated with entered email?

Hey I am trying to verify the password matches the one they entered with the email I have been searching for the web for a few hours and everything else I have tried does not work this is what i have so far:
try {
Class.forName(driver).newInstance();
Connection conn = (Connection) DriverManager.getConnection
(url + dbName, userName, password);
PreparedStatement checkUserInfo = (PreparedStatement) conn.prepareStatement
("SELECT password FROM profiles WHERE email = ?");
checkUserInfo.setString(1, emailT); //emailT is email pulled from an editText
//checkUserInfo.setString(2, pass1);
//Statement state = (Statement) conn.createStatement();
//String querychk = "SELECT * FROM profiles WHERE email = '"+emailT+"'";
//ResultSet rs = state.executeQuery(querychk);
ResultSet rs = checkUserInfo.executeQuery();
while (rs.next()){
String pass = rs.getString(2);
if (pass.equals(pass1)) {
return success;
}
}
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
Simply modify your SQL Query to:
"select * from profiles where email=? and password=?"
And be-aware to validate input fields for preventing from SQL injection
And for getting PreparedStatement object or Connection object, you don't have to externally typecast it, cause it is returning the same object as you assigning to it. Even java doc also provided the below statement for the PreparedStatement
PreparedStatement pstmt = con.prepareStatement(Query);

How to check if username already exist in the sql database before one can create new account using java

How can i put into code when i want to prompt a message whenever a user creates a new account or updates his/her username and that username already exist on the sql database.
here's a part of my code when i click save button on my CreateNewUserAccount class:
String sql = "insert into tblUserInfo (UserID, LastName, FirstName, PositionID, Username, Password) values(?, ?, ?, ?, ?, ?) " ;
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtUserID.getText());
pst.setString(2, txtLastName.getText());
pst.setString(3, txtFirstName.getText());
pst.setString(4, (String) comboPosition.getSelectedItem().toString().substring(0, 1));
pst.setString(5, txtUsername.getText());
pst.setString(6, txtPassword.getText());
pst.execute();
if(txtConfirmPassword.getText().equals(txtPassword.getText())){
JOptionPane.showMessageDialog(null, "Saved New User Account");
clear();
}
else{
JOptionPane.showMessageDialog(null, "Incompatible Password");
txtConfirmPassword.setText("");
}
//UpdateEmployeeTable();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
and also my UserAccount class where user can update/edit their information including their username:
String sql = "update tblUserInfo set LastName = ?, FirstName = ?, PositionID = ?, Username = ?, Password = ? where UserID= ?";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, txtLastName.getText());
pst.setString(2, txtFirstName.getText());
pst.setString(3, (String) comboPos.getSelectedItem().toString().substring(0, 1));
pst.setString(4, txtUserName.getText());
pst.setString(5, txtPassword.getText());
pst.setString(6, txtUserID.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "User Account Updated");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
how can i put a checking on this? Thanks in advance
I would use something like this
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
http://blogs.msdn.com/b/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx
One option is to do a count query of that username where the user id isn't the same, such as this:
select count(Username) from tblUserInfo where UserId != ?
If you find a result greater than zero, that user id is used by someone else, display the warning.
you can do like that
Statement st=con.getConnection(.....);
String query= "select username from tables where username="uservalue"";
ResultSet rs=st.executeQuery(query);
int value=0;
while(rs.next())
{
value++;
}
if(value>1)
{
String query= "select username from tables where username="uservalue"";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
String user=rs.getString("username");
}
String updatequery="update tables set username="updatevalue" where username="updatevalue"";
int q=st.executeupdate(updatequery);
}
else
{
insert query..........
}

Categories

Resources