我正在使用 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 '?'.
最佳答案
问题出在这里:
ResultSet rs = st.executeQuery(sql);
您正在使用Statement#executeQuery(String sql)
它继承自Statement
接口(interface)。您应该使用 PreparedStatement#executeQuery
.
简而言之,将该行更改为:
ResultSet rs = ps.executeQuery();
^ parameter-less
并从代码中删除此 Statement
变量,它只会让您和 future 的代码读者感到困惑:
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, customer.getId());
//Statement st = con.createStatement();
^ this generates confusion
此外,在 Java 中执行 SQL 语句时,应删除 SQL 语句中的分号:
String sql = "Select *"
+ " From Account"
+ " inner join CustomerAccount"
+ " on accountid = id"
+ " where customerid = ?";
关于java - 尝试在 java 中连接 2 个表,但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27064828/