⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 answerdaoimpl.java

📁 简易的java问答系统
💻 JAVA
字号:
package cn.netjava.dao.impl;

import java.sql.*;
import java.util.*;

import cn.netjava.dao.*;
import cn.netjava.dbc.DBConnection;
import cn.netjava.pojo.*;

/**
 * 答案类的具体实现
 * 
 * @author XieChengmin
 * 
 */
public class AnswerDAOImpl implements AnswerDAO {

	// 添加操作
	public boolean add(Answer a) {
		boolean inserted = false;
		String sql = "insert into answer values(seq_answerId.nextval, ?, ?, ?)";
		Connection con = DBConnection.getConn();
		PreparedStatement pst = null;

		try {
			pst = con.prepareStatement(sql);
			pst.setString(1, a.getAnswerContent());
			pst.setInt(2, a.getQ().getId());
			pst.setString(3, a.getOther());
			// 执行插入语句
			pst.execute();
			inserted = true;
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("ADD 方法: 数据连接创建失败或SQL语句有误");
		} finally {
			try {
				if (pst != null) {
					pst.close();
				}
				if (con != null) {
					// 放回连接池
					con.close();
				}
			} catch (SQLException e) {
				System.out.println("数据连接关闭失败");
			}
		}
		return inserted;
	}

	// 按ID查询
	public List<Answer> queryByQuestionId(int id) {
		List<Answer> all = new ArrayList<Answer>();
		String sql = "select * from answer where questionId = ?";
		Connection con = DBConnection.getConn();
		PreparedStatement pst = null;
		try {
			pst = con.prepareStatement(sql);
			// 执行查询语句
			pst.setInt(1, id);

			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				Answer a = new Answer();
				a.setId(rs.getInt(1));
				a.setAnswerContent(rs.getString(2));
				Question q = new QuestionDAOImpl().queryById(rs.getInt(3));
				a.setQ(q);
				a.setOther(rs.getString(4));
				all.add(a);
			} 
		} catch (SQLException e) {
			System.out.println("数据连接创建失败或查询SQL语句有误");
		} finally {
			try {
				if (pst != null) {
					pst.close();
				}
				if (con != null) {
					// 放回连接池
					con.close();
				}
			} catch (SQLException e) {
				System.out.println("数据连接关闭失败");
			}
		}

		return all;
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -