用户数据访问接口实现类UserDaoImpl
代码如下:
package net.lcn.student.bean.dao.impl;
import net.lcn.student.bean.bean.User;
import net.lcn.student.bean.dao.UserDao;
import net.lcn.student.bean.dbutil.ConnectionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 功能:用户数据访问接口实现类
* 2019.6.19
*/
public class UserDaoImpl implements UserDao {
/**
* 插入用户记录
*
* @param user
* @return 插入记录数
*/
@Override
public int insert(User user) {
//定义插入记录数
int count =0;
//1.获得数据连接
Connection conn = ConnectionManager.getConnection();
//2.定义SQL字符串
String strSQL = "insert into t_user (username, password, telephone, register_time) "
+ " values(?,?,?,?)";
try {
//3.创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
//4.设置占位符
pstmt.setString(1,user.getUsername());
pstmt.setString(2,user.getPassword());
pstmt.setString(3,user.getTelephone());
pstmt.setTimestamp(4,new Timestamp(user.getRegisterTime().getTime()));
//5.执行SQL,返回插入记录数
count = pstmt.executeUpdate();
//6.关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭数据库连接
ConnectionManager.closeConnection(conn);
}
//返回插入记录数
return count;
}
/**
* 按id删除用户记录
*
* @param id
* @return
*/
@Override
public int deleteById(int id) {
//定义删除记录数
int count = 0;
//1.获取数据库连接
Connection conn = ConnectionManager.getConnection();
//定义SQL字符串
String strSQL = "delete from t_user where id = ?";
try {
//创建预备语句
PreparedStatement pstme = conn.prepareStatement(strSQL);
//设置占位符的值
pstme.setInt(1,id);
count = pstme.executeUpdate();
//关闭预备语句对象
pstme.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {