JDBC中PreparedStatement中Like后面的参数
由于我们的项目不大,所以刚开始决定时我为了省事想用SSH,可是后来觉得只有Struts2好了,后来的查询等数据库操作我自己写方法不行了嘛!
刚才写一个公共查询的方法,在增加参数时出了点错误,就是使用模糊查询时犯晕了。
我写的方法如下:
-
/**
-
* @说明 执行一条查询SQL语句,可以带参数
-
*/
-
public static List<Object[]> excuteQuery(String sql, Object[] objs) {
-
Connection conn = null;
-
PreparedStatement psta = null;
-
ResultSet rs = null;
-
List<Object[]> iResult = null;
-
Object[] objArr = null;
-
try {
-
conn = getConn(); // 得到链接
-
PreparedStatement state = conn.prepareStatement(sql);
-
if(null != objs){
-
for (int i = 0; i < objs.length; i++) {
-
state.setObject(i + 1, objs[i]);
-
}
-
}
-
ResultSet resultSet = state.executeQuery(); // 执行查询,返回结果接集合
-
iResult = new ArrayList<Object[]>();
-
int count = resultSet.getMetaData().getColumnCount(); // 一共有多少列数据
-
while (resultSet.next()) {
-
objArr = new Object[count];
-
for (int i = 1; i <= count; i++) {
-
objArr[i - 1] = resultSet.getObject(i); // 增加到返回的集合中
-
}
-
iResult.add(objArr);
-
}
-
} catch (Exception e) {
-
e.printStackTrace();
-
iResult = null;
-
} finally {
-
try {
-
if (rs != null) {
-
rs.close();
-
}
-
if (psta != null) {
-
psta.close();
-
}
-
if (conn != null) {
-
conn.close();
-
}
-
} catch (Exception e2) {
-
-
}
-
}
-
return iResult;
-
}
后来我输入这样的一个参数进行查询:
-
public static void main(String[] args) {
-
Object[] para = new Object[]{"c"};
-
List<Object[]> list = excuteQuery("select * from s_user t where t.userName like '%?%'",para);
-
for (Object[] o : list) {
-
for (Object ob : o) {
-
System.out.print(ob + "-");
-
}
-
System.out.println();
-
}
-
}
结果报错如下:
-
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
-
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
-
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
-
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
-
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3279)
-
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3263)
-
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4087)
-
at com.mysql.jdbc.PreparedStatement.setObject(PreparedStatement.java:3513)
-
at org.apache.commons.dbcp.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:166)
-
at com.nms.common.db.ConnectionManager.excuteQuery(ConnectionManager.java:86)
-
at com.nms.common.db.ConnectionManager.main(ConnectionManager.java:20)
-
Exception in thread "main" java.lang.NullPointerException
-
at com.nms.common.db.ConnectionManager.main(ConnectionManager.java:21)
后来才知道,模糊查询时要这样写:
-
public static void main(String[] args) {
-
Object[] para = new Object[]{"%c%"};
-
List<Object[]> list = excuteQuery("select * from s_user t where t.userName like ?",para);
-
for (Object[] o : list) {
-
for (Object ob : o) {
-
System.out.print(ob + "-");
-
}
-
System.out.println();
-
}
-
}
就这么简单,闲话不说了!
欢迎大家访问我的博客来和我交流:http://cuisuqiang.iteye.com/