JSP PreparedStatement设置错误?在SQL查询中

时间:2012-05-11 00:26:51

标签: sql jsp variables prepared-statement

我有一段代码我在下面。请参阅:

Workload workload;
     ArrayList<Workload> workList = null;
     System.out.print("first");
     try{
         System.out.print("first");
         ConnectionFactory myFactory = ConnectionFactory.getFactory();
         Connection conn = myFactory.getConnection();
         int i = 0;


         PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM WORKLOAD WHERE datestart LIKE '? %'");
         PreparedStatement pstmtMember = conn.prepareStatement("SELECT * FROM MEMBER WHERE memberid = ? and deletestatus = 0");
         PreparedStatement pstmtLeader = conn.prepareStatement("SELECT * FROM LEADER WHERE leaderid = ? and deletestatus = 0");
         pstmt.setString(i++, startdate);

         ResultSet rs = pstmt.executeQuery();


         workList = new ArrayList<Workload>();

我的代码问题是它一旦到达pstmt.setString部分就“熄灭”。 我之所以选择LIKE'? %'是因为我只需要从查询中获取日期。不是整个时间戳。基本上它忽略了像'2012-04-05'这样的日期之后发生的事情。

1 个答案:

答案 0 :(得分:1)

你不能把单引号放在它周围,就像你只能对待它?就像它是一个在程序中写的变量

Like '@yourVar %' 

这相当于你所写的内容。

以下内容仅在日期存储在字符字段

中时才有效
String startDateWithPercent = startdate + " %"    
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM WORKLOAD WHERE datestart LIKE ?");
pstmt.setString(i++, startDateWithPercent);

如果数据库中datestart上的数据类型是datetime,则需要对数据库平台(这是sql server)执行相应的操作。只替换那个单独的prepareStatement行。

PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM WORKLOAD WHERE CONVERT(datestart,DATE) LIKE ?");