JDBC两种查询方法

//查询方法 返回值是以list形式返回的
public static List<Map<String, String>> executeQuery(String sql){
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
ResultSet rs = null;
Connection conn = null;
PreparedStatement stm = null;
try{
conn = getConnection();
stm = conn.prepareStatement(sql);
rs = stm.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
String[] names = new String[metaData.getColumnCount()];
for (int i = 0; i < metaData.getColumnCount(); i++) {
names[i] = (metaData.getColumnLabel(i + 1)).toLowerCase();
}
String str = "";
HashMap<String, String> tmp = new HashMap<String, String>();
while (rs.next()) {
tmp = new HashMap<String, String>();
for (int i = 0; i < names.length; i++) {
str = rs.getString(i + 1);
str = str == null ? "" : str.trim();
tmp.put(names[i], str);
}
list.add(tmp);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs != null)
rs.close();
if(conn != null)
conn.close();
if(stm != null)
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}

//更新,删除,新增方法
public static boolean updateQuery(String sql){
int effectRowNum = 0;
Connection conn = null;
PreparedStatement stm = null;
try{
conn = getConnection();
stm = conn.prepareStatement(sql);
effectRowNum = stm.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(conn != null)
conn.close();
if(stm != null)
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return effectRowNum == 1;
}

public static List execute(String sql, Class cla){
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
List ret = new ArrayList();
Field[] fields = cla.getDeclaredFields();
try{
conn = getConnection();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
ResultSetMetaData metaDate = rs.getMetaData();
int colCount = metaDate.getColumnCount();
while(rs.next()){
Object newInstance = cla.newInstance();
for(int i = 1; i <= colCount; i++){
Object value = rs.getObject(i);
if(value != null)
for(int j = 0; j < fields.length; j++){
Field f = fields[j];
if(f.getName().equalsIgnoreCase(metaDate.getColumnName(i))){
Class[] paraTypes = new Class[]{value.getClass()};
Method method = cla.getMethod("set" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1), paraTypes);
method.invoke(newInstance, new Object[]{value});
break;
}
}
}
ret.add(newInstance);
}
return ret;
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(rs != null)
rs.close();
if(conn != null)
conn.close();
if(pst != null)
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值