-1

我正在尝试withdraw and deposit 在 Bank Class 中为货币添加两种方法。我的Database name is javatest. table name is bank以下是代码。问题是当我运行这个代码编译器说 You have an error in your SQL syntax; 我确实检查了代码 3-4 次但真的无法得到它请帮助我。

public static void main(String[] args) 
{ 
    Connection connection= null ; 
    Statement stmt = null ; 
    try 
    {
        Class.forName("com.mysql.jdbc.Driver");
        connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/javatest","root","");
        stmt= connection.createStatement();
        withdrawfromchecking(connection, stmt, new BigDecimal(100), 1); 
        Depositinsaving(connection, stmt, new BigDecimal(444), 1);
        stmt.executeBatch();
        System.out.println("Done");
    } 
    catch (ClassNotFoundException e) {e.getMessage();}
    catch (SQLException e) {e.printStackTrace();}

    finally 
    {
        if(connection!=null){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}
        if(stmt!=null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}
    }
}


public static void withdrawfromchecking(Connection connection ,Statement stmt,  BigDecimal amount , int id ) throws SQLException
{
    stmt.addBatch("UPDATE bank  SET checkingbalance = checkingbalance-"+amount+"WHERE id="+id);
}
public static void Depositinsaving(Connection connection ,Statement stmt,  BigDecimal amount , int id ) throws SQLException
{
    stmt.addBatch("UPDATE bank  SET savingbalance = savingbalance+ "+amount+"WHERE id="+id);
}
}

此行出现错误 -stmt.executeBatch();当我运行程序时

编辑:确切的错误声明

java.sql.BatchUpdateException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在 MyPackage.BankAccount.main(BankAccount .java:24)

在我的代码中(第 24 行是 stmt.executeBatch();

4

3 回答 3

3

在你的两个 SQL 中,数量和单词的连接之间没有空格WHERE——它看起来像这样:checkingbalance-100WHERE id=.

WHERE在两个单词之前放置一个空格。

stmt.addBatch("UPDATE bank  SET checkingbalance = checkingbalance-"
  //       +- Add space here
  //       v
  +amount+" WHERE id="+id);
于 2013-08-07T23:44:27.090 回答
1

将您的withdrawfromcheckingDepositinsaving方法更改为:

public static void withdrawfromchecking(Connection connection, Statement stmt, BigDecimal amount, long id) throws SQLException{
        statement.addBatch("UPDATE bank SET checkingBalance = checkingBalance - " +amount+ " WHERE id =" + id);
    }

    public static void Depositinsaving(Connection connection, Statement stmt, BigDecimal amount, long id) throws SQLException{
        statement.addBatch("UPDATE bank SET savingBalance = savingBalance + " +amount+ " WHERE id =" + id);
    }
于 2014-12-09T22:03:48.177 回答
0

第一步是将更新语句放入字符串中并检查连接后的值。

理想情况下,您应该使用参数化准备好的语句,而不是动态连接 sql。

于 2013-08-08T01:43:08.190 回答