1. 程式人生 > >JDBC Spring 之JdbcTemplate 增刪改查操作

JDBC Spring 之JdbcTemplate 增刪改查操作

之前簡單介紹了JDBC CRUD的操作,接下來我為大家來講解一下JDBC 使用Spring框架來進行CURD(增刪改查操作)使用Spring中的JdbcTemplate之前應該給一個數據源來獲得連線。

package cn.itcast.jdbc;

import java.io.InputStream;
import java.sql.Connection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public final class JdbcUtils {
	private static String url = "jdbc:mysql://localhost:3306/JdbcTest";
	private static String user = "root";
	private static String password = "Qb393302+";
	private static DataSource myDataSource = null;

	private JdbcUtils() {

	}

	static {
		try {
			// 1.註冊
			Class.forName("com.mysql.jdbc.Driver");
			Properties prop = new Properties();
			InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
			prop.load(is);
			//使用的是DBCP方式來載入資料庫連線資訊
			myDataSource = BasicDataSourceFactory.createDataSource(prop);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	//獲得資料來源
	public static DataSource getDataSource() {
		return myDataSource;
	}
	public static Connection getConnection() throws SQLException {
		// return DriverManager.getConnection(url,user,password);
		return myDataSource.getConnection();
		
	}

	public static void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						conn.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
		}
	}
}
然後接下來我們來使用JdbcTemplate這個Spring模板類來進行CRUD操作。(記得在此之前應該引入spring.jar架包)如圖所示我所引入的包:


Spring -->CRUD操作:

<span style="font-size:24px;">package cn.itcast.jdbc.spring;

import java.util.Date;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import cn.itcast.jdbc.JdbcUtils;
import cn.itcast.jdbc.domain.User;

public class JdbcTemplateCreate {

	//獲取資料來源(設定為static 是因為該jdbc多次被呼叫)
	static JdbcTemplate jdbc = new JdbcTemplate(JdbcUtils.getDataSource());
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//這裡為測試CRUD程式碼塊
		User user = new User();
//		user.setName("小Q");
//		user.setBirthday(new Date());
//		user.setMoney(3000);
//		text1(user);
		user.setId(10);
//		user.setName("BB");
//		delete(user);
		user  = query(8);
		if (user == null) {
			System.out.println("查詢失敗");
		}else {
			System.out.println("查詢成功");
		}
	}
	
	//插入,增加
	public static void insert(User user) {
		String sql = "insert into user(name,birthday,money)values(?,?,?)";
		Object args[] = {user.getName(),user.getBirthday(),user.getMoney()};
		int temp = jdbc.update(sql, args);
		if (temp > 0) {
			System.out.println("插入成功!");
		}else{
			System.out.println("插入失敗");
		}
	}
	
	//刪除
	public static void delete(int id) {
		String sql = "delete from user where id = ?";
		Object args[] = new Object[]{id};
		int temp = jdbc.update(sql,args);
		if (temp > 0) {
			System.out.println("刪除成功");
		}else {
			System.out.println("刪除失敗");
		}
	}
	
	//更新
	public static void update(User user) {
		String sql = "update user set name = ? where id = ?";
		Object args[] = new Object[]{user.getName(),user.getId()};
		int temp = jdbc.update(sql,args);
		if (temp > 0) {
			System.out.println("更新成功");
		}else {
			System.out.println("更新失敗");
		}
		
	}
	
	//查詢
	public static User query(int id) {
		String sql = "select * from user where id = ?";
		Object args[] = new Object[]{id};
		Object  user = jdbc.queryForObject(sql,args,new BeanPropertyRowMapper(User.class));
		return (User)user;
	}

}
</span>

上面的User類是事先已經建立好的。
package cn.itcast.jdbc.domain;

import java.util.Date;


public class User {
	private int id;
	private String name;

	private Date birthday;
	private float money;

	public int getId() {
		return id;
	}

	

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public float getMoney() {
		return money;
	}

	public void setMoney(float money) {
		this.money = money;
	}

	public void setId(int id) {
		this.id = id;
	}

	

}
講到這裡,希望對大家有幫助。