understanding Java JDBC error

后端 未结 4 1688
野性不改
野性不改 2021-01-28 16:29

I was hoping to have some assistance in understanding this error. I am making a simple connection to a database, and for some reason it doesn\'t like my input, but I am failing

相关标签:
4条回答
  • 2021-01-28 16:38

    Change your makeDeposit() methods this line: In this case you are not paasing your variables, but they are used as simple strings.

    String sql = "insert into MYTABLE_TRANSACTIONS (ACCOUNT_ID,TRANSACTION_TYPE,AMOUNT) values(name, action, amount)";
    

    to

    String sql = "insert into MYTABLE_TRANSACTIONS (ACCOUNT_ID,TRANSACTION_TYPE,AMOUNT) values ("+name+", "+action+", "+amount+")";
    
    0 讨论(0)
  • 2021-01-28 16:44

    Never use plain statements with substitution. Use preparedStatement instead [ Read: When should we use a PreparedStatement instead of a Statement? ]

        String sql = "insert into MYTABLE_TRANSACTIONS (ACCOUNT_ID,TRANSACTION_TYPE,AMOUNT) values (?, ?, ?)";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1, name );
        pstmt.setString(2, action );
        pstmt.setDouble(3, amount);
    pstmt.executeUpdate();
    
    0 讨论(0)
  • 2021-01-28 16:46
    String sql = "insert into MYTABLE_TRANSACTIONS (ACCOUNT_ID,TRANSACTION_TYPE,AMOUNT) values ('" + name + "', '" + action + "', " + amount + ")";
    

    You need the single quotes for the name and action columns since they are of type varchar, and also you need the actual values so you need to build your query with '+' sign.

    /Nick

    0 讨论(0)
  • 2021-01-28 16:46

    The problem comes from the makeDeposit() method, specifically from these lines:

    String sql = "insert into MYTABLE_TRANSACTIONS (ACCOUNT_ID,TRANSACTION_TYPE,AMOUNT) values (name, action, amount)";
    stmt.executeUpdate(sql);
    

    Those values aren't right, you probably want some variable named name, not the actual string name.

    To provide a bit more insight, the error is a list of the methods that were ran until the error occurred. The one at the top is the most recent. So everything starts from the main() method, which runs the makeDeposit() method and then some methods that follow the call of stmt.executeUpdated(sql). Hope that clears it up.

    0 讨论(0)
提交回复
热议问题