试图在java中加入2个表,但我得到一个错误

时间:2014-11-21 15:31:36

标签: java sql join

我正在使用Sql和java。 这适用于sql:

use mybank
Select * from Account
inner join CustomerAccount on accountid = id
where customerid = 18

在java中我写这个:

String sql = ("Select * From Account inner join CustomerAccount on accountid = id where customerid =?;");
try (Connection con = myDbManager.getConnection())
{
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setInt(1, customer.getId());
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery(sql);

customer.getId给了我18个。

但是我得到了这个错误;

Incorrect syntax near '?'.

2 个答案:

答案 0 :(得分:4)

问题在于:

ResultSet rs = st.executeQuery(sql);

您正在使用从Statement接口继承的Statement#executeQuery(String sql)。您应该使用PreparedStatement#executeQuery

简而言之,将该行更改为:

ResultSet rs = ps.executeQuery();
                               ^ parameter-less

从代码中删除此Statement变量,只会让您和未来的代码混淆:

PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, customer.getId());
//Statement st = con.createStatement();
  ^ this generates confusion

此外,在从Java执行它时,应该删除SQL语句中的分号:

String sql = "Select *"
    + " From Account"
    + " inner join CustomerAccount"
    + " on accountid = id"
    + " where customerid = ?";

答案 1 :(得分:0)

Java中的SQL查询不要使用&#39 ;;':

String sql =( "Select * From Account inner join CustomerAccount on accountid = id where customerid =?");