Issue when querying Ms-Access database Java - java

I am trying to make a login page where a user enters their username an password and it is checked in the database and whether or not the record is found the user would be granted access to the rest of my program. But for some reason there seems to be an issue with my database query and I cannot quite figure out why.
My code is below:
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
try
{
String userInput = txtUsername.getText();
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con = DriverManager.getConnection("jdbc:ucanaccess://E:/Documents/School/IT/2020 PAT Database.accdb");
pst = con.prepareStatement("select * from tblLoginDetails WHERE Username = " + userInput);
rs = pst.executeQuery();
ResultSetMetaData rsd = rs.getMetaData();
String ID, username = "", password, isAdmin;
while(rs.next())
{
ID = rs.getString("ID");
username = rs.getString("Username");
password = rs.getString("Password");
isAdmin = rs.getString("IsAdmin");
if(username.equalsIgnoreCase(txtUsername.getText()))
JOptionPane.showMessageDialog(null, "Its working!");
}
}
//Exception handling for ClassNotFoundException and SQLException:
catch (ClassNotFoundException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Class Not Found\n"+e);
}
catch (SQLException e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Invalid input\n"+e);
}
}
});
When i click on the login button I get an input error saying that the object is not found or user lacks privilege. Any help would be much appreciated.

Related

mysql connector doesn't connect to my xxamp localhost

I am using netbeans 8.2 with xxamp. mysql connector.jar is 8.0.18.
It doesn't show any errors but whenever I press the button, the value from jUsername isn't inserted and instead the exception in the catch is shown. Please help.
private void StartButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
String query = "INSERT INTO 'score' ('Name') VALUES (?)";
con = DriverManager.getConnection("jdbc:mysql://localhost/userscore", "root", "");
pst = con.prepareStatement(query);
pst.setString(1, jUsername.getText());
DifficultyPanel dpanel =new DifficultyPanel();
dpanel.setVisible(true);
this.dispose();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Please Enter Your Username To Continue");
}
}

Connect Java with Mysql

I am trying to connect a Neteans Java project with Mysql database and i cannot establish a connection and i do not know what could possibly go wrong
My Java code:
private void setupLoginEventListener() {
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rightFirstText = userName.getText();
rightText = password.getPassword();
if (rightFirstText.isEmpty() && rightText.length == 0) {
JOptionPane.showMessageDialog(JavaApplication6.this, "All fields are required", "Error", JOptionPane.ERROR_MESSAGE);
} else if (rightText.length == 0) {
JOptionPane.showMessageDialog(JavaApplication6.this, "Password is required", "Error", JOptionPane.ERROR_MESSAGE);
} else {
try {
conn = getDBConnection();
pst = conn.prepareStatement("select * from pdie where username =? and password=?");
pst.setString(1, rightFirstText);
pst.setString(2, new String(rightText));
rs = pst.executeQuery();
while (rs.next()) {
JOptionPane.showMessageDialog(JavaApplication6.this, "Login Successfull");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(JavaApplication6.this, "Login Failed");
}
}
}
});
}
public Connection getDBConnection() {
Connection con = null;
String url = "jdbc:mysql://localhost:3536/";
String dbName = "projectdb";
String driver = "com.mysql.jdbc.Driver";
String connectUserName = "root";
String connectPassword = "";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + dbName, connectUserName, connectPassword);
System.out.println("CONNECTION ESTABLISHED.");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("CONNECTION COULD NOT BE ESTABLISHED.");
}
return con;
}
any ideas?
it gives me an error for null pointer exception in this line
pst = conn.prepareStatement("select * from pdie where username =? and password=?");
type these lines
st=con.createStatement();
String sql="SELECT * FROM TAB";
rs=st.executeQuery(sql);
and try to print a a field; to test quickly if the problem is in you prepared statement but probably it's in your conn object.

How can I get the username after successful login?

I am trying to display username after user Login to the system in Java. There have any way?
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JDBC driver name and database URL
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost/unimas";
// Database credentials
final String USER = "root";
final String PASS = "shojib420";
Connection conn = null;
Statement stmt = null;
try {
dec();
} catch (NoSuchAlgorithmException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//String name=name2.getText();
String username=user1.getText();
//String faculty=fac1.getText();
if(username.equalsIgnoreCase("") || password.equalsIgnoreCase(""))
{
JOptionPane.showMessageDialog(contentPane, "OOPS You miss some filed");
}
else
{
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
/* String sql="INSERT INTO useruser " +
"VALUES (username,password, name,faculty)";*/
String sql="SELECT * FROM useruser WHERE username='"+username+"' and password='"+password+"' ";
ResultSet rs=stmt.executeQuery(sql);
if(rs.next())
{
dashboard d=new dashboard();
d.setVisible(true);
d.name=username;
dispose();
}
else
{
JOptionPane.showMessageDialog(contentPane, "Sorry "+password);
}
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e1){
//Handle errors for Class.forName
e1.printStackTrace();
}
}
}
});
Here d.name=username; name is in the dashboard class where I am trying to set d.name=username; , But i am not able to get the value of username
JTextArea showName = new JTextArea();
showName.setBounds(29, 25, 105, 22);
contentPane.add(showName);
showName.setName(name);
I am calling that name in dashboard class. Any idea where I am doing wrong or better suggestion?
dashboard d=new dashboard();
d.setVisible(true);
d.name=username;
Here you just set class variable but the variable is not set in any label (or textarea or textfield).
Should be
dashboard d=new dashboard();
d.nameLabel.setText(username);
d.setVisible(true);

Check login string against password (MySQL & JDBC)

I know there's plenty of other questions out there with a similar topic but I can't find one that creates a solution to my specific problem. I have a Java Application that connects via JDBC to Lamp for a Uni project and I'm trying to compare the inputted password to the password related to the login they also entered in the MySQL database. I have a hashing (MD5) method that will hash the users input but it keeps throwing a null pointer exception and I can't fix it!
on button press code:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String pass = passTextField.toString();
try {
try {
lModel.checkLogin(loginTextField.getText(), pass);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException se) {
System.out.println(se.toString());
}
}
Hashing method (and related variables):
private Logins l;
private String password;
public String hashPass(String pass) throws NoSuchAlgorithmException {
MessageDigest mdEnc = MessageDigest.getInstance("MD5");
mdEnc.update(password.getBytes(), 0, password.length());
String md5 = new BigInteger(1, mdEnc.digest()).toString(16); // Encrypted
return md5;
}
Check Login method (without connection String for privacy):
public void checkLogin(String login, String pass) throws SQLException, NoSuchAlgorithmException {
Connection con = null;
PreparedStatement stmt= null;
ResultSet rs = null;
l = new Logins();
String passHashed = hashPass(pass);
String username = login;
try {
stmt = con.prepareStatement("SELECT Login, Password from Staff");
rs = stmt.executeQuery();
if (rs.next()) {
if (username.equals(rs.getString("Login"))) {
if (passHashed.equals(rs.getString("Password"))) {
System.out.println("Logged in.");
} else {
System.out.println("Incorrect password - login combination.");
}
} else {
System.out.println("Incorrect log in.");
}
}
} finally {
if (rs != null) try {rs.close();} catch (SQLException se){}
if (stmt != null) try {stmt.close();} catch (SQLException se) {}
if (con != null) try {con.close();} catch (SQLException se) {}
}
}
Edit: It all parses correctly and can check the database but I've found the reason it doesn't log in ever is because the MD5 code generated by the method produces a different output to that of the password stored in the database. Here's the database one:
1274d1c52d7a5a9125bd64f1f9a26dce
and the generated:
1030416151603361603636256577523441305746075
The password is LondonWeight
Any ideas?
password is not set to the value of pass pararmeter so password.getBytes() won't work. What about pass.getBytes()
con appears to always be null
You need to obtain a connection object before you can do con.prepareStatement("SELECT Login, Password from Staff");
There may be other problems in your code, but it's hard to tell which problem you are hitting without a stacktrace
Has your Staff table got more than one row in it? Seems like unless the user name that you are loking for isd the first one returned by your SQL statement, then you'll get "Incorrect Log in" . Would n't you be better doing
SELECT Login, Password from Staff where Login = UserName
( that isn't syntactically correct in your context but you get the drift ... )
That way, if don;t get a row, then it's an Incorrect Login, and then you just have to compare the hashed values.

how to read object from servlet in android

I am developing a android application that has to talk with the servlet to access the database. I want to pass the object from servlet to my android application.
This my servlet code to send object.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text");
String id = request.getParameter("id");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
java.sql.Connection con= DriverManager.getConnection("jdbc:odbc:Database");
Statement statement = con.createStatement();
PrintWriter p = response.getWriter();
ResultSet rs = statement.executeQuery("select * from employee where PS="+id);
while(rs.next()){
Employee e = new Employee();
e.setId(rs.getString("ID"));
e.setPs(String.valueOf(rs.getDouble("PS")));
e.setName(rs.getString("Emp_name"));
e.setDept(rs.getString("Dept"));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(e);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How should i read the object in my android application.
Thanks.
Well you can do various things to solve this problem
a)Use DAO practice here Read it to understand it basically it divides the implementation of your code into different segments and classes for your ease.
But if you dont want to go through all that trouble You can do some thing like.
a.) Create a separate java class where you write all the methods to deal with the Db like insert,select etc..
e.g if your loggin in the user.. than the method would be like this..
public int AuthenticateUser(String un, String pw, String phn) {
System.out.println("I m in this method");
Connection conn = (Connection) DBConnection.getInstance().getConnection();
Statement pstmt = null;
ResultSet rs = null;
if (conn == null) {
System.out.println("Connection error");
check = -1;
}
try {
String authenticatequery = "SELECT * FROM users WHERE uname = '"+un+"' && password = '"+pw+"' && phoneno = '"+phn+"'";
System.out.println(authenticatequery);
pstmt = conn.createStatement();
rs = pstmt.executeQuery(authenticatequery);
System.out.println("I m in above try catch");
// pstmt = conn.prepareStatement(authenticatequery);
// rs = pstmt.executeQuery(authenticatequery);
if (rs.next()) {
System.out.println("I am in rs method");
UserInfo info = new UserInfo();
rs.getString(1);
rs.getString(2);
rs.getString(3);
//info.setUsername(rs.getString(un));
System.out.println("i have the username" + un);
//info.setPassword(rs.getString(un));
System.out.println("I have got the password " + pw);
System.out.println("I have got the password " + phn);
System.out.println("User Exist");
check = 1;
} else {
System.out.println("No user found");
check = 0;
}
// rs.close();
// pstmt.close();
// conn.close();
} catch (SQLException e) {
// TODO: handle exception
System.out.println("Exception-internal error");
} finally {
if (conn != null) {
try {
conn.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return check;
}
Notice the int variable "check" if the method runs correctly it will return '1' else '0'.. Now u can use this check for your advantage and send it to your android app via servlet like this..
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//String username = request.getParameter("username");
// String password = request.getParameter("password");
//UserInfo uinfo = new UserInfo();
// uinfo.setUsername(username);
// uinfo.setPassword(password);
System.out.println("I am in process");
PrintWriter out = response.getWriter();
String un, pw,phn;
un = request.getParameter("Usrnm");
System.out.println(un);
pw = request.getParameter("pwd");
System.out.println(pw);
phn = request.getParameter("phn");
System.out.println(phn);
Authenticate auth = new Authenticate();
int check = auth.AuthenticateUser(un, pw,phn);
System.out.println("My result is" + check);
if (check==1){
out.print(1);
} else{
out.print(0);
}
}
}
In your android app you can call the the response object using the code below, do add custom http client class for the comunitcation.
response = CustomHttpClient.executeHttpPost("http://192.1..11../HelloWorldServlet/LoginDriverServlet", postParameters);
Now you can play with the response object and mould it to suit your needs
if (res.equals("1")) {
Log.e("CHeck4 response","i m here");
Log.e("CHeck response", res);
//error.setText("Correct Username or Password");
Intent intent = new Intent(getApplicationContext(), SetStatus.class);
startActivity(intent);
setContentView(R.layout.activity_set_status);
Toast.makeText(getApplicationContext(), "Loggin In", Toast.LENGTH_LONG).show();
} else if(res.equals("0")) {
//error.setText("Sorry!! Incorrect Username or Password");
Log.e("CHeck3 response", "i m here");
Toast.makeText(getApplicationContext(), "Sorry!! Incorrect Username or Password", Toast.LENGTH_LONG).show();
Intent intent = new Intent();
//Username or Password",Toast.LENGTH_LONG).show();
}
Hope you get it..otherwise coments are welcomed :)

Categories