How to update only a certain parameters of the object? - java

I have a user object in the database, which has the following parameters: username, password, email, admin(boolean).
I want to change only username and that's it. I don't want to touch other fields. The problem with this is that I need to pass a new value for every parameter of the object. My current method, which updates user information looks like this:
String query = "";
query = "UPDATE users SET username=?, password=?, email=?, admin=? where id=?";
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
connection = DriverManager.getConnection(Constant.URL + Constant.DB_NAME, "root", "");
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, user.getUsername() );
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getEmail());
preparedStatement.setBoolean(4, user.isAdmin());
preparedStatement.setShort(5, id);
preparedStatement.execute();
} catch (SQLException e){
throw new RuntimeException(e.getMessage(), e);
} finally {
closeResource(connection, preparedStatement);
}
My update method in the controller:
public static void updateAccountInformation() {
UserDao userDao = new UserDao();
short id = Constant.LOGGED_IN_USER_ID;
System.out.println("Your current account information: ");
System.out.println("Enter new username: ");
String username = sc.nextLine();
System.out.println("Enter new password: ");
String password = sc.nextLine();
System.out.println("Enter new email: ");
String email = sc.nextLine();
System.out.println("Change admin status: ");
boolean admin = sc.nextBoolean();
//parameters i need to pass to the user object
User user = new User();
try {
userDao.updatePersonalInfo(user, id);
System.out.println("User updated successfully!");
} catch (RuntimeException e) {
System.out.println("Something went wrong!");
}
What solution you would suggest in this situation?

Related

Is there any other better way to get and compare database credentials with java?

I am trying to create a simple login system with java using mySQl database.
I have stored user ID and password in a database table.
I've come up with a way to login which seems to work well but i am not sure if it's the right way to do it, as i couldn't find any online source for login systems.
My steps are :
getting input from the user (user ID and password).
Using the fetch() method that i created to iterate through the table and finding this specific ID.
If it's found, get the password and balance from the table and store them in variables.
Finally compare the password that i previously got from the database and stored in a variable with the password inputed from the user.
I am well aware that storing passwords in plain text is a big security hole, but for now i am just trying to learn the way to use the data from the DB in my java program
This is my code:
public class firstjava extends Database {
public static int UID = 0;
public static String password;
public static int BAL;
public static String upassword;
static void fetch(int userid) throws SQLException {
String query = "SELECT * FROM Persons";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
int ID = rs.getInt("pid");
if (ID == UID) {
password = rs.getString("password");
BAL = rs.getInt("balance");
}
}
if (upassword.equals(password)) {
System.out.println("you are now logged in");
} else {
System.out.println("incorrect password");
}
st.close();
}
public static void menu() throws IOException, SQLException {
Scanner atm = new Scanner(System.in);
System.out.println("enter your account number");
UID = atm.nextInt();
System.out.println("enter your account password");
upassword = atm.next();
fetch(UID);
}
public static void main(String[] args) throws IOException, SQLException {
Database db = new Database();
try {
db.connect();
} catch (Exception e) {
e.printStackTrace();
}
menu();
db.close();
}
}
You can directly pass userId as parameter to your query and fetch password and balance from DB Table then you should compare password with user entered password.
static void fetch(int userid) throws SQLException
{
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM Persons where pid = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1,userid);
rs = ps.executeQuery(); //instantiate rs with executed query
while(rs.next()) {
password = rs.getString("password");
BAL = rs.getInt("balance");
}
if(upassword.equals(password)) {
System.out.println("you are now logged in");
} else {
System.out.println("incorrect password");
}
rs.close();
ps.close();
}
"If I have been able to see further, it was only because I stood on the shoulders of giants."
Here is the giant:
https://spring.io
You'll find something like:
Optional<User> r = userRepo.findByName(name);
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
if (passwordEncoder.matches(password, user.getPassword())) {
// ...
}

java.sql.SQLExecption:parameter index out of range (1>number of prameters, which is 0) for update sql

i have problem with my project, and it still new for me with MYSQL, i want to get data from database and do some calculation and update the value on it,
its like making withdraw function like ATM machine. This my table look like.
enter image description here . You can see constructor parameter that carry value (String value and String ID). For Value="100"; and ID="5221311" you can see it on my table picture.
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
You are already setting the parameters on the query, so It tries to set the parameters and find no parameters to find. Try this:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";

Data displays after actual SQL insert into query and not via my netbeans query

Below is code to my UserArray which connects to my database and has a method to insert a new user based off data taken from a gui i created (when a create button is clicked) [see second bit of code]
public class UserArray
{
private Connection conn = null;
public UserArray(String db)
{
try
{
String filename = db;
conn = DriverManager.getConnection("jdbc:ucanaccess://" + filename,"","");
}
catch (Exception e)
{
System.out.println("Error: " + e);
}
}
public void InsertNewUser (String fn, String ln, String hn, String sn, String cn,
String pc, String un, String pass)
{
try
{
Statement st = conn.createStatement();
String sql = "INSERT INTO Users (Username, Password, FirstName, LastName, "
+ "HouseNumber, StreetName, CityName, PostalCode) "
+ "VALUES ('"+un+"', '"+pass+"', '"+fn+"', '"+ln+"', '"+hn+"','"+sn+"', '"+cn+"', '"+pc+"')";
st.execute(sql);
}
catch (SQLException se)
{
System.out.println("ERROR " + se);
}
}
}
Below is the code for my GUI when the create button is 'hit' once all details have been entered
private void btnCreateActionPerformed(java.awt.event.ActionEvent evt)
{
String fn = txtFirstName.getText(); //new user enters their first name
String ln = txtLastName.getText(); //new user enters their last name
String hn = txtHouseNum.getText(); //new user enters their house number
String sn = txtStreetName.getText(); //new user enters their street name
String cn = txtCity.getText(); //new user enters their city name
String pc = txtPostCode.getText(); //new user enters their postal code
String un = txtUsername.getText(); //new user enters their username
String pass = pwdPassword.getText(); //new user enters their password
String repass = pwdREPassword.getText(); //new user re-enters their password
UserArray ua = new UserArray("kickZA.accdb");
if (repass.equals(pass))
{
ua.InsertNewUser(fn, ln, hn, sn, cn, pc, un, pass);
}
else
{
JOptionPane.showMessageDialog(this, "passwords to not match");
}
}

How to use an MySQL database to authenticate a user?

I'm trying to authenticate a user (login) in java using MySQL database. I want to be able to do this in the console. This is what i have so far: My main class-
import java.util.Scanner;
public class main {
public static void main(String args[]){
if (args.length < 2)
return;
login meth = new login();
Scanner in = new Scanner(System.in);
String username;
String password;
System.out.println("");
System.out.println("Username: ");
username = in.next();
System.out.println("2. Account Holder");
password = in.next();
System.out.println("");
meth.loginDetails(username, password);
login checker = new login();
boolean rc = checker.loginDetails(args[0], args[1]);
System.out.println("The result is: " + Boolean.toString(rc));
in.close();
}
}
And this is my class where i attempt to connect to the database and query it.
import java.sql.*;
public class login {
public void databaseConnection(){ //swapping index a and index b around
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/loginTest","root", "");
System.out.println("Database is connected !");
conn.close();
}
catch(Exception e){
System.out.println("Do not connect to DB - Error:"+e);
}
}
static final String CONN_URL = "jdbc:mysql://localhost/loginTest";
static final String DB_USER = "root";
static final String DB_PASSWORD = "";
public boolean loginDetails(String accountNumber, String password){
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
boolean passwdOK = false;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(CONN_URL, DB_USER, DB_PASSWORD);
// Create and execute an SQL statement
String sqlst = "SELECT Password FROM customer " +
" WHERE Account Number = '" + accountNumber + "'";
stmt = con.createStatement();
rs = stmt.executeQuery(sqlst);
// Check the return data
if (rs.next()) {
String passwdSaved = rs.getString(1).trim();
if (passwdSaved.equals(password.trim()))
passwdOK = true;
}
rs.close();
stmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
return passwdOK;
}
}
My database is called Customer and the separate columns are called Account Number, Password.
At the moment when i run the program it gets instantly terminated. Without showing any of the print lines.
So my question is how do i get a result true or false, that the user name and password is a match. And if it was false, let them retry and if its true load a switch menu?
First of all change
boolean rc = checker.loginDetails(args[0], args[1]);
to
boolean rc = checker.loginDetails(username, password);
If you are not running this program with arguments then args[0] and args[1] will throw ArrayIndexOutOfBoundException

multi-user login java (admin,user,teacher)

I have three user types in database.
http://oi44.tinypic.com/2z8qflw.jpg
And heres my login form
http://oi44.tinypic.com/20p5v04.jpg
When i choose admin as usertype, enter the username and password from the database, the admin form shows up. But when i choose teacher and student, and type the username&pass from the database, only the JOptionpane shows up which is the Invalid details.
heres my code for login jframe:
JButton btnLogin = new JButton("Login");
btnLogin.setFont(new Font("Book Antiqua", Font.PLAIN, 18));
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql = "SELECT * FROM useRecords ";
try {
ps = conn.prepareStatement(sql);
rs=ps.executeQuery();
String user = usern.getText();
String pwd = new String (passw.getPassword());
String type =(String)typeUser.getSelectedItem();
while(rs.next()) {
String uname = rs.getString("username");
String pass = rs.getString("password");
if ((user.equals(uname)) && (pwd.equals(pass))) {
if (type.equals("Admin")) { // ... admin
dispose();
aCai aCai = new aCai();
aCai.setVisible(true);
aCai.setExtendedState(Frame.MAXIMIZED_BOTH);
} else if (type.equals("Teacher")) { // ... teacher
dispose();
tCai tCai = new tCai();
tCai.setVisible(true);
tCai.setExtendedState(Frame.MAXIMIZED_BOTH);
} else {
dispose();
sCai sCai = new sCai();
sCai.setVisible(true);
sCai.setExtendedState(Frame.MAXIMIZED_BOTH);
}
} else {
JOptionPane.showMessageDialog(null, "User name and password do"
+ " not match!","ALERT!",
JOptionPane.ERROR_MESSAGE);
break;
}
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
try{
rs.close();
ps.close();
} catch(Exception e) {
}
}
}
});
The problem is, you are asking for ALL the rows from the useRecord table and looping through the result set. When you fail to find a match for the username or password on the FIRST row, you show the JOptionPane and break out of the loop, preventing any other possible checks
while(rs.next()) {
String uname = rs.getString("username");
String pass = rs.getString("password");
if ((user.equals(uname)) && (pwd.equals(pass))) {
//...
} else {
JOptionPane.showMessageDialog(null, "User name and password do"
+ " not match!","ALERT!",
JOptionPane.ERROR_MESSAGE);
break;
}
}
A better approach might be to ask the database for all the results that match the username and password directly, for example...
String user = usern.getText();
String pwd = new String (passw.getPassword());
String type =(String)typeUser.getSelectedItem();
String sql = "SELECT * FROM useRecords where username=? and password=? and type = ?";
try {
ps = conn.prepareStatement(sql);
ps.bindString(1, user);
ps.bindString(2, pwd);
ps.bindString(3, type);
rs=ps.executeQuery();
ps- As a side note, you should avoid storing passwords using plain text in this manner (in fact you should avoid storing them in String). Personally, I would use some kind of one-way hash algorithm to store password in the database, this way, if the database is compromised, then it won't matter (alot) if they get the passwords - IMHO

Categories