lxw
2023-10-13 fbec698fe9301e8f9f6283c3823cb0734191c292
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.whyc.service;
 
import com.whyc.mapper.CallBack;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
 
@Service
public class MybatisSqlExecuteService {
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
 
    //    自定义执行SQL
    public List executeQuery(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;
    }
 
    //    开启链接
    private SqlSession openSession() {
        SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
        return sqlSessionFactory.openSession();
    }
 
    //    关闭链接
    private void closeSession(ResultSet rs,PreparedStatement ps,SqlSession sqlSession) {
        try {
            rs.close();
            ps.close();
            sqlSession.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}