Mybatis中执行String类型的自己拼写的sql,不执行配置文件中的sql
在自己的dao类中继承SqlSessionDaoSupport类
/**
* @author herman.xiong
* @since 0.1
* @param <T>实体类
* @param <PK>主键类,必须实现Serializable接口
*/
package com.dao;
import java.io.Serializable;
import org.apache.log4j.Logger;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.ArrayList;
import java.util.List;
public class TestSqlDao extends SqlSessionDaoSupport{
//日志管理器
private static final Logger log=Logger.getLogger(TestSqlDao.class);
//测试自己拼写的sql
public List<Integer> testStringSql(String sql){
List<Integer> list=new ArrayList<Integer>();
Connection con=this.getSqlSession().getConnection();
PreparedStatement ps=null;
ResultSet rs=null;
try {
ps = con.prepareStatement(sql);
rs=ps.executeQuery();
while (rs.next()) {
list.add(rs.getInt("id"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
log.error("关闭结果集ResultSet异常!"+e.getMessage(), e);
}
}
if(ps!=null){
try {
ps.close();
} catch (Exception e) {
log.error("预编译SQL语句对象PreparedStatement关闭异常!"+e.getMessage(), e);
}
}
if(con!=null){
try {
con.close();
} catch (Exception e) {
log.error("关闭连接对象Connection异常!"+e.getMessage(), e);
}
}
}
return list;
}
public static void main(String[] args) {
TestSqlDao tsd=new TestSqlDao();
List<Integer> list=tsd.testStringSql("select id from table");
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
}
一下是本人自己测试的输出结果截图:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有