0

guys. I learn java from few weeks and now i tried to insert my data from simple bank account application into MySQL table (the id and the name from the main class, and the balance and previous transaction from the other class). I want to save the balance and transactions when use particular name and id. This is my code:

import java.sql.*;
import java.util.Scanner;

public class BankingApp {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.next();
        System.out.print("Enter your ID: ");
        String id = sc.next();
        
        System.out.println();

        BankAccount bankAcc = new BankAccount(name, id);
        bankAcc.showMenu();

        bankAcc.insert();

        sc.close();
    }
}

class BankAccount {

    float balance;
    float prevTransaction;
    String customerName;
    String customerID;

    BankAccount(String name, String id) {
        customerName = name;
        customerID = id;
    }

    void deposit(float amount) {

        if (amount != 0) {
            balance += amount;
            prevTransaction = amount;
        }
    }

    void withdraw(float amount) {

        if (amount != 0) {
            balance -= amount;
            prevTransaction = -amount;
        }
    }

    void getPreviousTransaction() {

        if (prevTransaction > 0) {
            System.out.println("Deposited: " + prevTransaction);
        }
        else if (prevTransaction < 0) {
            System.out.println("Withdrawn: " + Math.abs(prevTransaction));
        }
        else {
            System.out.println("No transaction is occured!");
        }
    }

    void showMenu() {

        char option = '\0';

        Scanner sc = new Scanner(System.in);

        System.out.println("Welcome " + customerName);
        System.out.println("Your ID is: " + customerID);
        System.out.println();
        System.out.println("A. Check Balance");
        System.out.println("B. Deposit");
        System.out.println("C. Withdraw");
        System.out.println("D. Previous Transaction");
        System.out.println("E. Exit");

        do {
            System.out.println("=========================");
            System.out.println("Enter the option");
            System.out.println("=========================");
            option = sc.next().charAt(0);
            Character.toUpperCase(option);

            switch (option) {
                case 'A':
                    System.out.println("============================");
                    System.out.println("Balance: " + balance);
                    System.out.println("============================");
                    System.out.println();
                    break;
                
                case 'B':
                    System.out.println("============================");
                    System.out.println("Enter the amount to deposit");
                    System.out.println("============================");
                    float amount = sc.nextFloat();
                    deposit(amount);
                    System.out.println();
                    break;
                
                case 'C':
                    System.out.println("============================");
                    System.out.println("Enter the amount to withdraw");
                    System.out.println("============================");
                    float amount2 = sc.nextFloat();
                    withdraw(amount2);
                    System.out.println();
                    break;

                case 'D':
                    System.out.println("============================");
                    getPreviousTransaction();
                    System.out.println("============================");
                    System.out.println();
                    break;

                case 'E':
                    System.out.println("============================");
                    break;

                default:
                    System.out.println("Invalid Option! Please try again!");
                    break;
            }
        
        } while (option != 'E');
    
        sc.close();
    } 

    public void insert() {

        String myUrl = "jdbc:mysql://localhost:3306/bankacc";
        String db_id = "root";
        String db_pass = "Ik32e23k";

        Connection conn = null;
        Statement stmt = null;

        try {    
        conn = DriverManager.getConnection(myUrl, db_id, db_pass);
        stmt = conn.createStatement();
            
        String sql = "insert into users" +
                     "(id, name, balance, transactions)" +
                     "values (" + customerID + ", " + customerName + ", " + balance + ", " + prevTransaction +")";

        stmt.executeUpdate(sql);    
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

When i tried to call my insert() method into the main method, i got the following error:

java.sql.SQLSyntaxErrorException: Unknown column 'Koko' in 'field list' at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:121) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1334) at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2084) at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1245) at BankAccount.insert(BankingApp.java:151) at BankingApp.main(BankingApp.java:18)

Instead of inserting my name into the table, the exception told me that my name is unknown column. I have only guesses where the problem could be coming from, but I have no idea how to do it. Can somebody explain me where is my bad? Thanks in advance!

  • 5
    Now would be a good time to learn about parameterized SQL. That will not only avoid this sort of problem, but will protect your app from SQL Injection Attacks. You might also want to look at the value of the `sql` variable in the debugger. – Jon Skeet Jul 05 '23 at 12:52
  • If your column(s) data type is varchar, you need to have `'` in your `values(`. Which you are missing. – Pradeep Simha Jul 05 '23 at 12:53
  • 2
    Use parameterized queries instead of concatenating variables into the query string! This is much safer (prevents SQL injection), and will avoid the problem you are currently facing. – GMB Jul 05 '23 at 12:53
  • @PradeepSimha Thank you, the problem was the missing single quotes around one of the columns. :) – Kostadin Samardjiev Jul 05 '23 at 13:07

1 Answers1

0

String sql = "insert into users" + "(id, name, balance, transactions)" + "values (" + customerID + ", '" + customerName + "', " + balance + ", " + prevTransaction +")";

You have to use ' when inserting string. But it is better to user prepared statements. If the values you entered has already characters like ' .

Example: sql="INSERT INTO raporlar (raporNo,hastaID,hastaTC,protokol,tarih,tur,tesiskod,tesis,takipno) " + "VALUES (?,?,?,?,?,?,?,?,?);"; PreparedStatement ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); ps.setString(1, raporno);ps.setInt(2, hastaID); ps.setString(3, hastatc);ps.setString(4, protokol); ps.setString(5, raporTarih);ps.setString(6, raporturu); ps.setString(7, hastanekod);ps.setString(8, hastaneadi); ps.setString(9, takipno); ps.execute(); ResultSet generatedKeys = ps.getGeneratedKeys(); if (generatedKeys.next()) { raporID=(generatedKeys.getInt(1)); }

  • Thanks, it works for the insertion. But may i ask why when i run the program again i cant use same user while enter the same name and id, instead of that the program just duplicate it in the database? =/ – Kostadin Samardjiev Jul 05 '23 at 13:17
  • You have to check and get the user information from database.... like... ResultSet rs=stmt.executeQuery("SELECT * FROM WHERE user='blabla'") and then get the password and check if it matches. and also get the related information... like money in the account... if (rs.next()) { String password=rs.getString("pass"); } – Özgür Liman Jul 05 '23 at 13:23
  • Please format your answer correctly. – tgdavies Jul 05 '23 at 13:31