更灵活的使用PrepareStatement接口
public viod findResultSet(String sql, Object[] paras) {
//....
PrepareStatement pstat =
conn.preparement(sql);
//ParamentMetaData pmd =
pstat.getParamenterMetaData();
//int count
= pmd.getParamenterCount();
// String
sql = "select name from user where name=? and password=?";
for (int i =
0; i < paras.length; i++)
//初始化sql里的占位符 如:pstat.setString(1, "name");
pstat.setString(2, "password");
pstat.setObject(i+1, paras[i]);
pstat.executeQuery();
//...
}
调用处1:
String sql = "select name from user where name=? and password=?";
Object[] paras = new Object[]{"lisi", "123"};
findResultSet(sql, paras);
调用处2:
String sql = "select name, password, address from user where id > ? and name=? and password=?";
Object[] paras = new Object[]{1, "lisi", "123"}; //分别对应三个问号的内容
findResultSet(sql, paras);
不需要修改函数的具体代码。
可以根据不同的参数实现了查询不同的记录!!增加了灵活性。
}
调用处1:
String sql = "select name from user where name=? and password=?";
Object[] paras = new Object[]{"lisi", "123"};
findResultSet(sql, paras);
调用处2:
String sql = "select name, password, address from user where id > ? and name=? and password=?";
Object[] paras = new Object[]{1, "lisi", "123"};
findResultSet(sql, paras);
不需要修改函数的具体代码。
可以根据不同的参数实现了查询不同的记录!!增加了灵活性。
版权声明:本文为博主原创文章,未经博主允许不得转载。