SpringJdbc queryForList 不加查询条件

springjdbc是个非常好用的jdbc框架,但是在编程时遇到一个很蛋疼的事,描述如下:

 

执行一条类似下面不带where条件的sql语句时:

select * from table

用到了queryForList(String sql, Object... args) 方法,然后懵了,这第二个参数,到底怎么弄?

 

刚开始是这么写的:

 

springjdbc.queryForList("select * from table", null);[
 

 

然后报错了。。

 

然后又想起来一招:

 

springjdbc.queryForList("select * from table where 1=?", 1);
 

 

我擦,这么的确行,就用了一段时间。

 

过了几天回过来看代码时,觉得这样好二,然后看到 Object... args 领悟到点什么,于是就索性这样了:

 

springjdbc.queryForList("select * from table");
 

 

执行,通过了。。。

 

嗯,对, Object... args 就是这么imba。

 

贴一下完整的一个例子

 

 

package jdbc;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class Ha {

	static String urlLocal = "jdbc:mysql://localhost:3306/test?user=root&password=root";
	
	public static void main(String[] args) {
		SimpleJdbcTemplate jdbcLocal = config(urlLocal);
		
		test(jdbcLocal);
	}
	
	public static void test(SimpleJdbcTemplate jdbc) {
		String sql = "select * from stu";
		List<Map<String, Object>> list = jdbc.queryForList(sql);
		list.get(0);
	}
	
	public static SimpleJdbcTemplate config(String url) {
		
		MysqlDataSource mds = new MysqlDataSource();
		mds.setUrl(url);
		
		try {
			mds.getConnection().close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return new SimpleJdbcTemplate(mds);
	}
	
}
 

 

你可能感兴趣的:(SpringJDBC)