Java:在表中输入值的SQL语法错误

时间:2013-08-07 23:42:33

标签: java mysql sql database jdbc

我想在Bank Class中为withdraw and deposit钱添加两种方法。我的Database name is javatesttable 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服务器版本对应的手册   正确的语法在第1行的'id = 1'附近使用   com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:1193)at at   MyPackage.BankAccount.main(BankAccount.java:24)

我的代码中的

(第24行是stmt.executeBatch();

3 个答案:

答案 0 :(得分:3)

在两个SQL中,金额和单词WHERE的串联之间没有空格 - 它看起来像这样:checkingbalance-100WHERE id=

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

stmt.addBatch("UPDATE bank  SET checkingbalance = checkingbalance-"
  //       +- Add space here
  //       v
  +amount+" WHERE id="+id);

答案 1 :(得分:1)

撤销检查存款保存方法更改为:

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);
    }

答案 2 :(得分:0)

第一步是将update语句放在一个字符串中,并在连接后检查该值。

理想情况下,您应该使用参数化prepared statements而不是动态连接sql。