一.什么是Dao?
dao是数据访问对象,用来封装对数据库的访问,用它将数据库中的表转换为DTO类,就是转化为我们上一节封装的用户类和地址类。
二.建一个接口:负责插入功能,更新功能和删除功能
package com.langzimingjian.dao;
import java.sql.Connection;
import com.langzimingjian.entity.User;
public interface UserDao {
/**
* 保存用戶信息的save方法
*/
public void save(Connection connection, User user) throws Exception;
public void update(Connection connection,long id, User user)throws Exception;
public void delete(Connection connection,User user) throws Exception;
}
三建个类实现接口:
<pre name="code" class="java">package com.langzimingjian.dao.impi;import java.sql.Connection;import java.sql.PreparedStatement;import com.langzimingjian.dao.UserDao;import com.langzimingjian.entity.User;public class UserDaoimpi implements UserDao {/** * 保存用戶信息 */public void save(Connection connection, User user) throws Exception {// TODO Auto-generated method stubPreparedStatement ps = connection.prepareStatement("insert into tbl_user(name,password,email)values(?,?,?)");ps.setString(1, user.getName());ps.setString(2, user.getPassword());ps.setString(3, user.getEmail());ps.execute();}/** * 根據指定的id更新用戶信息 */public void update(Connection connection, long id, User user)throws Exception {// TODO Auto-generated method stubString updateSql = "update tbl_user set name=?,password=?,email=?where id=?";PreparedStatement ps = connection.prepareStatement(updateSql);ps.setString(1, user.getName());ps.setString(2, user.getPassword());ps.setString(3, user.getEmail());ps.setLong(4, id);ps.execute();}/** * 刪除指定的用戶信息 */public void delete(Connection connection, User user) throws Exception {// TODO Auto-generated method stubPreparedStatement ps = connection.prepareStatement("delete form tbl_user where id = ?");ps.setLong(1, user.getId());ps.execute();}}
新建一个测试类:
package com.langzimingjian.test;
import java.sql.Connection;
import com.langzimingjian.dao.UserDao;
import com.langzimingjian.dao.impi.UserDaoimpi;
import com.langzimingjian.entity.User;
import com.langzimingjian.utils.ConnectionFactory;
public class UserDaoTest {
public static void main(String[] args) {
Connection connection = null;
try {
connection = ConnectionFactory.getInstance().makeConnection();
connection.setAutoCommit(false);
UserDao userDao = new UserDaoimpi();
User katelin = new User();
katelin.setName("katelin");
katelin.setPassword("123456789");
katelin.setEmail("katelin@qq.com");
userDao.save(connection, katelin);
connection.commit();
} catch (Exception e) {
// TODO: handle exception
try {
connection.rollback();
if(connection!= null){
connection.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
测试结果:
成功。看完之后感觉套路很深,明天从新看下原码,看下mvc。