No DataSource specified

使用jdbcTemplate操控数据库结果出现如下错误:

No DataSource specified_第1张图片


 

错误代码如下

package cn.com.compent;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import cn.com.bean.Port;

public class TemplateJDBC {
/*author:命运的信徒
 * date:2019/02/27
 * arm:通过templatjdbc来操控数据库
 */
	
	public static void main(String[] args) {
		select();
	}
	public static void select(){
		JdbcTemplate jt=new JdbcTemplate();
		String sql="select * from Port";
		RowMapper rowMapper=new BeanPropertyRowMapper(Port.class);
		Port li=jt.queryForObject(sql, rowMapper);
		System.out.println(li.toString());
		
	}
}

错误原因:

没有加载spring的配置文件容器


正确代码如下

package cn.com.compent;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import cn.com.bean.Port;

public class TemplateJDBC {
/*author:命运的信徒
 * date:2019/02/27
 * arm:通过templatjdbc来操控数据库
 */
	
	public static void main(String[] args) {
		select();
	}
	public static void select(){
		ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
		JdbcTemplate jt=(JdbcTemplate) ioc.getBean("jdbcTemplate");
		String sql="select * from Port";
		RowMapper rowMapper=new BeanPropertyRowMapper(Port.class);
		List li=(List) jt.queryForObject(sql, rowMapper);
		for (Port port : li) {
			System.out.println(port.toString());
		}
		
	}
}

 

你可能感兴趣的:(java之ssh框架专栏)