我正在尝试创建一个sql查询构建器类型程序,该程序使用用户输入数据为表构建自定义查询
到目前为止我已经
了public int checkBetweenDates() throws SQLException{
String t1 = "2015-07-08"; //or later some user input variable
String t2 = "2015-07-09";//or later some user input variable
String id = "22 03 E7 99";//or later some user input variable
int rowCount = -1;
//Statement stmt = null;
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between (t1) and (t2)"
+ "and id = (id)"
+ "values (?)";
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(dateChoice);
preparedStmt.setString (1, t1);
// preparedStmt.setString (2, t2);
// preparedStmt.setString (3, id);
// stmt = conn.createStatement();
ResultSet rs = preparedStmt.executeQuery(dateChoice);
try {
rs = preparedStmt.executeQuery(dateChoice);
rs.next();
rowCount = rs.getInt(1);
System.out.println(rowCount);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
rs.close();
preparedStmt.close();
}
return rowCount;
}
所以它连接并且一切正常,但是它没有执行查询说sql语法错误的值(?,?,?)
任何帮助都会很棒,谢谢你们!
卡尔
答案 0 :(得分:1)
尝试此操作,查询中的更改以及设置预准备语句参数
public int checkBetweenDates() throws SQLException{
String t1 = "2015-07-08"; //or later some user input variable
String t2 = "2015-07-09";//or later some user input variable
String id = "22 03 E7 99";//or later some user input variable
int rowCount = -1;
//Statement stmt = null;
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between ? and ?"
+ "AND id = ?";
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("Connected:");
PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(dateChoice);
preparedStmt.setString (1, t1);
preparedStmt.setString (2, t2);
preparedStmt.setString (3, id);
// stmt = conn.createStatement();
ResultSet rs = preparedStmt.executeQuery(dateChoice);
try {
rs = preparedStmt.executeQuery(dateChoice);
rs.next();
rowCount = rs.getInt(1);
System.out.println(rowCount);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
rs.close();
preparedStmt.close();
}
return rowCount;
}
如果不适合您,请分享确切的错误。
答案 1 :(得分:0)
改变这个:
String dateChoice = "select count(*) "
+ "from dancers "
+ "where ts between (t1) and (t2)"
+ "and id = (id)"
+ "values (?)";
根据您使用的数据库语法。例如,如果您使用带有Mysql的Web服务器,请输入查询以查看拼写错误的位置。 (如果你使用mysql,每个表需要dancers
)
答案 2 :(得分:0)
首先,您似乎已多次编辑此方法以尝试解决问题,这使其处于混乱状态。
从sql语句中删除“values(?)”,它不属于此处,似乎是从准备好的insert语句中遗留下来的。
调用带有零参数的preparedStmt.executeQuery(),你已经为它提供了sql字符串并且只将它命名为ONCE,你为rs赋值两次。
你的sql语句应该包含三个问号,试试
select count(*) from dancers where ts between ? and ? and id = ?
接下来调用prepareStmt.setString()三次来提供值t1,t2和id。
另外,请记住在finally块中关闭连接对象。