您的位置:首页 > 其它

大一实训第三天状态数据访问接口实现类StatusDaoImpl

2019-06-28 15:25 246 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_40781005/article/details/94007147
package net.tc.student.dao.impl;

import net.tc.student.bean.Status;
import net.tc.student.dao.StatusDao;
import net.tc.student.dbutil.ConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StatusDaoImpl implements StatusDao {

@Override
public Status findById(int id) {
// 声明状态量
Status status = null;
// 1.获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 2.定义sql字符串
String strSQL = "select * from t_status where id = ?";
try {
// 3.创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4.设置占位符的值
pstmt.setInt(1, id);
// 5.执行sql查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 6.判断结果集是否有记录
if (rs.next()) {
// 实例化状态
status = new Status();
// 利用当前记录字符值去设置状态对象的属性
status.setId(rs.getInt("id"));
status.setCollege(rs.getString("college"));
status.setVersion(rs.getNString("version"));
status.setAuthor(rs.getString("author"));
status.setTelephone(rs.getString("telephone"));
status.setAddress(rs.getString("address"));
status.setEmail(rs.getString("email"));
}
// 7.关闭预备语句对象
pstmt.close();
// 8.关闭结果集对象
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回状态对象
return status;
}

@Override
public int update(Status status) {
// 定义更新记录数
int count = 0;
// 1.获取数据库连接
Connection conn = ConnectionManager.getConnection();
// 2.定义sql语句
String strSQL = "UPDATE t_status SET college = ?, version = ?, author = ?,"
+ " telephone = ?, address = ?, email = ? WHERE id = ?";
try {
// 3.创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 4.设置占位符的值
pstmt.setString(1, status.getCollege());
pstmt.setString(2, status.getVersion());
pstmt.setString(3,status.getAuthor());
pstmt.setString(4, status.getTelephone());
pstmt.setString(5, status.getAddress());
pstmt.setString(6, status.getEmail());
pstmt.setInt(7, status.getId());
// 5.执行更新操作,更新记录
count = pstmt.executeUpdate();
// 6.关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回更新条数
return count;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: