check if value (Accountnumber) exist in a java database - java

I have the following method in a class called savings, am using JDBC database to save and view data on java application.
I have SAVINGS table in my database ZaiLab with the following fields,
ID,ACCOUNTNUMBER,CUSTOMERNAME,BALANCE,MINMUM)
and the following VALUEs will be entered by the user using JOPtionPane.
(id,accountNumber,customername,balance,minmum);
the application should then check if accountNumber entered by the user already exist, if not it should save the record to a table SAVINGS, if yes it should display the appropriate message. "Account already exist".
public void openSavingsAccount(int Id, int Amount) {
try {
String host = "jdbc:derby://localhost:1527/ZaiLab";
String uname = "siduduzo";
String upass = "Password01";
Connection con = DriverManager.getConnection(host, uname, upass);
Statement stmt = con.createStatement();
String SQL = "SELECT * FROM SAVINGS";
ResultSet rs = stmt.executeQuery(SQL);
int minmum = 1000;
balance = minmum;
while (rs.next()) {
int acc_col = rs.getInt("ACCOUNTNUMBER");
if (acc_col == accountNumber) {
JOptionPane.showMessageDialog(null, "Sorry, account " + accountNumber
+ " aready Exist");
} else if (Amount < minmum) {
JOptionPane.showMessageDialog(null, "Can not Open the Account, Minimum amount to deposit must be R1000");
} else {
balance = balance + Amount;
id = Id;
stmt.executeUpdate("INSERT INTO `SAVINGS`(ID,ACCOUNTNUMBER,CUSTOMERNAME,BALANCE,MINMUM)VALUE ('" + id + "','" + accountNumber + "','" + customername + "'," + balance + ",'" + minmum + "')");
}
}
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}

Right now you are selecting all rows from SAVINGS and attempt to insert a new account for each row that doesn't have the 'new' account number.
Instead, you should select only the row with the new account number, and insert when it doesn't exist.
You should also use prepared statements to protect you against SQL injection.
For example:
try (PreparedStatement checkAccountExists = con.prepareStatement(
"SELECT 1 FROM SAVINGS WHERE ACCOUNTNUMBER = ?")) {
checkAccountExists.setInt(1, accountNumber);
try (ResultSet rs = checkAccountExists.executeQuery()) {
if (rs.next()) {
// handle account already exists
} else {
try (PreparedStatement insert = con.prepareStatement(
"INSERT INTO SAVINGS(ID, ACCOUNTNUMBER, CUSTOMERNAME, BALANCE, MINMUM) VALUES (?, ?, ?, ? , ?)")) {
insert.setInt(1, id);
insert.setInt(2, accountNumber);
insert.setString(3, customername);
insert.setInt(4, balance);
insert.setInt(5, minmum);
insert.executeUpdate();
}
}
}
}
Alternatively, you could define a unique constraint on ACCOUNTNUMBER in your database and just do the insert and handle the constraint violation if the record already exists.

Related

I have a card database that has the columns (String cardnumber, String pin, double balance) and I am having issues making a deposit to card

Here is my method for the deposit method, I have tried making a deposit but the balance is stays at 0.0 which is the initial value. I am a little confused I am able to print the balance fine in another method but when it comes to updating I am having no luck. I would appreciate some help for my method.
public void deposit(String number, String pin, double amount) {
String sql = "UPDATE cards " +
"SET balance = ?" +
"WHERE number = ? AND pin = ?";
try(Connection c = this.connect();
PreparedStatement statement = c.prepareStatement(sql)) {
statement.setString(1, number);
statement.setString(2, pin);
statement.executeUpdate();
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
double x = rs.getDouble(3);
double t = x + amount;
statement.setDouble(3, t);
}
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
}
There are 3 parameters that you must pass:
statement.setDouble(1, amount);
statement.setString(2, number);
statement.setString(3, pin);
statement.executeUpdate();
Also, you should have a space after "SET balance = ?":
String sql = "UPDATE cards " +
"SET balance = ? " +
"WHERE number = ? AND pin = ?";
But since you are doing a deposit, maybe you want to add the amount to the current balance, so change the query to this:
String sql = "UPDATE cards " +
"SET balance = balance + ? " +
"WHERE number = ? AND pin = ?";
Also, this:
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
double x = rs.getDouble(3);
double t = x + amount;
statement.setDouble(3, t);
}
is pointless.
The string sql contains an UPDATE statement which does not return a ResultSet.

Access is denied when I am executing an update query with Ucanaccess

I have just started with ucanaccess and I am attempting to work out how it works. I wanted to update my Access database's username from "Sutaciba" to "Evan" but it shows the following error:
"Exception occured:
UCAExc:::4.0.4 C:\Users\evanc\AppData\Roaming\IT PAT DataBase (Access is denied)".
Seems like Ucanaccess doesn't have permission to gain access to my database for some reason.
Thank you for any help!
public static void main(String args[])
{
int ID = 1;
String username = "Sutachiba";
String password = "Evanchui123";
String email = "evanchui34#gmail.com";
try
{
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\evanc\\AppData\\Roaming\\IT PAT DataBase");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [username], [password] FROM [tblUser] WHERE ID =" + ID);
while(rs.next())
{
username = rs.getString(1);
password = rs.getString(2);
email = rs.getString(3);
System.out.println("Username: " + username + '\n' + "Password: " + '\n' + "Email:" + email);
}
String newN = "Evan";
String updateQuery = "UPDATE userDB SET (username) = (?) WHERE ID =" + ID;
PreparedStatement st = conn.prepareStatement(updateQuery);
st.setString(1, newN);
st.executeUpdate();
System.out.println("Successfully updated userdata!");
conn.close();
}
catch(Exception ex)
{
System.err.println("Exception occured: ");
System.err.println(ex.getMessage());
}

java/sql comparing two ints

I have the following function and I am trying to compare the number of students enrolled in a class with the class max. If the number enrolled is greater than the class max, I want to return a message that says, "The Class if Full".
public static void classFullCheck() {
try {
String currentNumberInClassAsString = ("SELECT class_id, COUNT(*) FROM ClassSelector.student_x_class WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(currentNumberInClassAsString);
int currentNumberInClassAsInt = 0;
if(rs.next()){
currentNumberInClassAsInt = rs.getInt(1);
}
String classSizeAsString = ("SELECT class_size FROM ClassSelector.classes WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(classSizeAsString);
int classSizeAsInt = 0;
if(rs.next()){
classSizeAsInt = rs.getInt("class_size");
}
if (currentNumberInClassAsInt > classSizeAsInt){
System.out.println("Sorry, this class is Full!");
}
} catch (java.sql.SQLException SQL) {
SQL.printStackTrace();
}
}
I am inserting the classFullcheck() function into the addClass() function like this:
public static void addClass() {
try {
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes");
while (rs.next()) {
String availableClasses = rs.getString("class_id") + "\t" + rs.getString("class_name") + "\t" + rs.getString("description");
System.out.println(availableClasses);
}
System.out.println("Enter Class ID from Classes Listed Above to Join: ");
selectedClass = sc.nextLine();
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
System.out.println(innerJoin);
String student_x_classJoin = "INSERT INTO student_x_class" + "(student_id, student_name, class_id, class_name)" + "VALUES (?, ?, ?, ?)";
PreparedStatement pStmt = con.prepareStatement(student_x_classJoin);
pStmt.setString(1, user_entered_student_id);
pStmt.setString(2, userEnterIdAsName);
pStmt.setString(3, rs.getString("class_id"));
pStmt.setString(4, rs.getString("class_name"));
pStmt.executeUpdate();
System.out.println("Would you like to enroll " + userEnterIdAsName + " into another class? (Y/N)");
String addAdditionalClass = sc.nextLine();
if (addAdditionalClass.equalsIgnoreCase("Y")) {
addClass();
} else if (addAdditionalClass.equalsIgnoreCase("N")) {
return;
}
}
}
catch (java.sql.SQLException SQL) {
System.out.println("Wait, This Student is already enrolled in this class!");
}
}
I am currently just getting both messages printed out, even if a class is not full. Any suggestions would help a lot.
if (currentNumberInClassAsInt >= classSizeAsInt) {
String updateStatus = "Update ClassSelector.classes SET status = ? WHERE class_id = " + selectedClass;
PreparedStatement pStmt = con.prepareStatement(updateStatus);
pStmt.setString(1, "Closed");
pStmt.executeUpdate();
System.out.println("Sorry, this class is Full! Select a different Class:");
System.out.println("\nSign Up For a Class\n");
addClass();
}
I think you want this:
currentNumberInClassAsInt = rs.getInt(2);
instead of:
currentNumberInClassAsInt = rs.getInt(**1**);
I don't think the ResultSet is 0 based...
Also is rs a global variable because it looks like you are changing your ResultSet rs when you call classFullCheck(). You may not have what you think you do in the ResultSet...
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();//****************result set changed here******************
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
You may think you have this: rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass); in your result set but you change rs in classFullCheck(). You may want to store the data in a different object that way when you run another query you can still access the data.

Unable to retrieve first column

I am trying to get the first column (column id and get the associated first and last name). I have tried multiple things but unable to get it to work.
It returns me with error CUSTOMERID not found.
public String getCustomerUsingId(int id) {
String firstName = null;
String lastName = null;
Statement stmt = null;
String getCustomerQuery = "SELECT FIRSTNAME,LASTNAME FROM CUSTOMERS WHERE CUSTOMERID ='"
+ id + "'";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
stmt.execute(getCustomerQuery);
ResultSet rs = stmt.getResultSet();
if(rs.next()){
id = rs.getInt("CUSTOMERID");
System.out.println("id is:" + id);
if(id == -1){
System.out.println("value is true");
firstName = rs.getString(2);
lastName = rs.getString(3);
System.out.println("First Name :" + firstName);
System.out.println("First Name :" + lastName);
}
}
}
I am using H2 as database and this is what is looks like
CUSTOMERID FIRSTNAME LASTNAME
1 P S
2 K S
This is how I have created the table
String customerSqlStatement = "CREATE TABLE CUSTOMERS " + "(customerId INTEGER NOT NULL IDENTITY(1,1) PRIMARY KEY, " + " FirstName VARCHAR(255), " + " LastName VARCHAR(255))";
You also need to explicitly include the column name in the select query.
So, the variable getCustomerQuery should be something like
String getCustomerQuery = "SELECT CUSTOMERID,FIRSTNAME,LASTNAME FROM CUSTOMERS WHERE CUSTOMERID ='"
+ id + "'";

How do I delete a row from database table in Java

I am trying to develop a simple Java DVD library console app in Java. I have created a database table that contains a list of DVD's. I have managed to get the adding a new DVD to the database functionally working, but I am struggling to delete a row from the database. When I use a SQL statement to select a row (row 7) then run the line 'rs.delete' I get the following exception:-
Invalid cursor state - no current row.
Below is my database table:-
ID Film Name Genre Rating
-------------------------------
1 Robocop Sci-fi 18
2 Terminator Sci-fi 18
3 Alien Sci-fi 18
4 Big Fish Fantasy PG
5 The Pianist Drama 18
6 Total Recall Sci-fi 18
7 Carnage Comedy 18
Below is copy of my code. Please could somebody help?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dvdlibrary;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import java.util.Scanner;
/**
*
* #author Andy
*/
public class DVDLibrary {
Connection con;
Statement stmt;
ResultSet rs;
String selection = "";
int id_num =0;
String film_name ="";
String genre ="";
String rating="";
public DVDLibrary()
{
DoConnect();
}
public void DoConnect() {
try
{
String host = "jdbc:derby://localhost:1527/DVDLibrary";
String username = "andyshort";
String password = "Pa55word";`enter code here`
con = DriverManager.getConnection(host, username, password);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM ANDYSHORT.DVDS";
rs = stmt.executeQuery(SQL);
/*
System.out.println("ID Film Name Genre Rating");
System.out.println("-------------------------------");
while (rs.next())
{
int id_col = rs.getInt("ID");
String film_name_col = rs.getString("Film_Name");
String genre_col = rs.getString("Genre");
String rating_col = rs.getString("Rating");
String p = id_col + " " + film_name_col + " " + genre_col + " " + rating_col;
System.out.println(p);
//System.out.format("%32s%10d%16s", id_col , film_name_col, genre_col, rating_col);
}
*/
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
public void GetUserInput()
{
System.out.println();
System.out.println("What would you like to do? Choose one of the following options.");
System.out.println("1. Display DVD library list");
System.out.println("2. Add a new film to database.");
System.out.println("3. Delete a film from the database.");
System.out.println();
Scanner user_option_selection = new Scanner(System.in);
selection = user_option_selection.next();
if(selection.equalsIgnoreCase("1"))
{
DisplayDVDList();
}
else if(selection.equalsIgnoreCase("2"))
{
AddRecord();
}
else if(selection.equalsIgnoreCase("3"))
{
DeleteRecord();
}
else
{
System.out.println("Incorrect option entered. Please try again.");
}
}
public void DisplayDVDList()
{
try
{
String SQL = "SELECT * FROM ANDYSHORT.DVDS";
rs = stmt.executeQuery(SQL);
System.out.println("ID Film Name Genre Rating");
System.out.println("-------------------------------");
while (rs.next())
{
int id_col = rs.getInt("ID");
String film_name_col = rs.getString("Film_Name");
String genre_col = rs.getString("Genre");
String rating_col = rs.getString("Rating");
String p = id_col + " " + film_name_col + " " + genre_col + " " + rating_col;
System.out.println(p);
//System.out.format("%32s%10d%16s", id_col , film_name_col, genre_col, rating_col);
}
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
public void AddRecord()
{
Scanner new_film_details = new Scanner(System.in);
System.out.println("Please enter film name: ");
film_name = new_film_details.next();
System.out.println("Please enter film genre: ");
genre = new_film_details.next();
System.out.println("Please enter film rating: ");
rating = new_film_details.next();
try
{
rs.last();
id_num = rs.getRow();
id_num = id_num + 1;
rs.moveToInsertRow();
rs.updateInt("ID", id_num);
rs.updateString("FILM_NAME", film_name);
rs.updateString("GENRE", genre);
rs.updateString("RATING", rating);
rs.insertRow();
//stmt.close( );
//rs.close( );
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
public void DeleteRecord()
{
String id = "";
Scanner id_of_film_to_delete= new Scanner(System.in);
System.out.println("Enter ID of film you want to delete.");
id = id_of_film_to_delete.next();
int idInt = Integer.parseInt(id);
try
{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
rs = stmt.executeQuery(sql);
rs.deleteRow();
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
}
use directly this query
"DELETE FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
String sql = "DELETE FROM ANDYSHORT.DVDS WHERE ID=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "+ idInt+");
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println(" delete successfully!");
}
Use prepared statements to avoid SQL injection:
PreparedStatement statement;
statement = con.prepareStatement("DELETE FROM andyshort.dvds WHERE id = ?");
statement.setInt(1, idToDelete);
statement.executeUpdate();
You can directly use delete query if you have the Id before hand.
String sql = "DELETE FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
stmt.executeUpdate(sql);
But, it's better to use prepared statements instead of statements in order to avoid sql injection attacks.
String query= "DELETE FROM ANDYSHORT.DVDS WHERE ID = ? ";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1,idInt);
preparedStatement.executeUpdate();
You need to move the cursor to the first row before deleting the row, if you want to use deleteRow() method.
rs.first();
rs.deleteRow();

Categories

Resources