2014-11-21 36 views
0

我正在使用Sql和Java。 这个作品在SQL:试图在Java中加入2个表,但我得到一个错误

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 '?'. 
+0

不工作,它出于安全原因:) – 2014-11-21 15:34:18

回答

4

的问题是在这里:

ResultSet rs = st.executeQuery(sql); 

您使用Statement#executeQuery(String sql)这是从Statement继承接口。你应该使用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 = ?"; 
+0

我相信你的意思是指示他使用'ps.executeQuery()'(不是'st')。 – 2014-11-21 15:39:17

+0

@JohnBollinger对。发布编辑。 – 2014-11-21 15:40:18

+0

是的,制定出来了,谢谢:) 但我不能接受答案只是... – 2014-11-21 15:42:33

0

SQL查询在Java中不使用 ';':

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