spring jdbctemplate 实现数据库的查询操作

package com.mx.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;



public class testDao {

	public static void main(String[]args){
		DriverManagerDataSource dd = new DriverManagerDataSource();
		dd.setDriverClassName("com.mysql.jdbc.Driver");
		dd.setUrl("jdbc:mysql:///spring");
		dd.setUsername("root");
		dd.setPassword("root");
		JdbcTemplate jt = new JdbcTemplate(dd);
		String sql = "insert into user values(?,?,?)";
		//往数据表中添加数据
		//int rows = jt.update(sql,1,"mx","123");
		//查询数据
		String sql2 = "select * from user where name=?";
		user User = jt.queryForObject(sql2, new MyrowMapper(), "hwr");
		System.out.println(User);
	}
}

class MyrowMapper implements RowMapper{

	@Override
	public user mapRow(ResultSet rs, int num) throws SQLException {
		// TODO Auto-generated method stub
		String username = rs.getString("name");
		String password = rs.getString("password");
	
		user U = new user();
	    U.setUsername(username);
	    U.setPassword(password);
		return U;
	}
	
}

package com.mx.dao;

public class user {

	String username;
	String password;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "user [username=" + username + ", password=" + password + "]";
	}
	
}

如果想查询表中的所有的结果,只需要改:

1) sql=select * from user;

2)List list = jt.query(sql2,new MyrowMapper()); 

3)System.out.println(list)即可

你可能感兴趣的:(Spring)