| | |
| | | package com.whyc.service; |
| | | |
| | | import com.whyc.mapper.CallBack; |
| | | import com.whyc.util.ActionUtil; |
| | | import net.sf.json.JSONArray; |
| | | import net.sf.json.JSONObject; |
| | | import org.apache.ibatis.session.SqlSession; |
| | |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | import java.sql.PreparedStatement; |
| | | import java.sql.ResultSet; |
| | | import java.sql.ResultSetMetaData; |
| | | import java.sql.SQLException; |
| | | import javax.swing.*; |
| | | import java.sql.*; |
| | | import java.util.List; |
| | | |
| | | @Service |
| | |
| | | while (rs.next()) { |
| | | JSONObject jsonObject = new JSONObject(); |
| | | for(int i=1;i<=colCnt;i++){ |
| | | jsonObject.put(metaData.getColumnName(i),rs.getObject(i)); |
| | | String property=metaData.getColumnName(i); |
| | | Object obj=rs.getObject(i); |
| | | if(obj instanceof java.util.Date ){ |
| | | jsonObject.put(property, ActionUtil.sdf.format(obj)); |
| | | }else{ |
| | | jsonObject.put(property,obj); |
| | | } |
| | | } |
| | | JSONObject.toBean(jsonObject,Object.class); |
| | | jsonArray.add(jsonObject); |
| | | } |
| | | } catch (SQLException throwables) { |
| | |
| | | return jsonArray; |
| | | } |
| | | |
| | | // 自定义执行SQL |
| | | public List executeQuery_call(String sql, CallBack call){ |
| | | PreparedStatement ps = null; |
| | | ResultSet rs = null; |
| | | SqlSession sqlSession = openSession(); |
| | | try { |
| | | ps=sqlSession.getConnection().prepareStatement(sql); |
| | | rs=ps.executeQuery(); |
| | | return call.getResults(rs); |
| | | } catch (SQLException throwables) { |
| | | throwables.printStackTrace(); |
| | | }finally { |
| | | closeSession(rs,ps,sqlSession); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 封装所有更新的操作(添加,删除,修改) |
| | | * @param sql |
| | | * @param values |
| | | * @return |
| | | */ |
| | | public boolean executeUpdate(String sql, Object[] values){ |
| | | PreparedStatement ps = null; |
| | | ResultSet rs = null; |
| | | SqlSession sqlSession = openSession(); |
| | | try { |
| | | ps = sqlSession.getConnection().prepareStatement(sql); |
| | | if(values != null){ |
| | | for (int i = 0; i < values.length; i++) { |
| | | ps.setObject(i+1, values[i]); |
| | | } |
| | | } |
| | | int flag = ps.executeUpdate(); |
| | | if(flag>0){ |
| | | return true; |
| | | } |
| | | } catch (SQLException e) { |
| | | e.printStackTrace(); |
| | | }finally{ |
| | | closeSession(rs,ps,sqlSession); |
| | | } |
| | | return false; |
| | | } |
| | | // 开启链接 |
| | | private SqlSession openSession() { |
| | | SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory(); |