📄 webmsgdao.java
字号:
package cn.edu.zucc.news.model;
import java.sql.*;
import java.util.*;
public class WebMsgDAO {
private Connection conn = null;
private Statement st = null;
public WebMsgDAO() {
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
conn = DriverManager
.getConnection(
"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=j2ee_news",
"sa", "123456");
st = conn.createStatement();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public synchronized void release() {
if (st != null) {
try {
st.close();
} catch (Exception e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
public synchronized List loadAllMsgs() throws Exception{
List result = new ArrayList();
try {
ResultSet rs = st.executeQuery("select * from tb_msg");
while (rs.next()) {
WebMsg msg=new WebMsg();
msg.setMsg_id(rs.getInt("msg_id"));
msg.setUserid(rs.getString("userid"));
msg.setMsg(rs.getString("msg"));
msg.setSend_time(rs.getDate("send_time"));
result.add(msg);
}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("数据库查询错误");
}
return result;
}
public synchronized void addMsg(String userid,String msgs) throws Exception{
try {
String sql="insert into tb_msg(userid,msg,send_time) values('"+userid+"','"+msgs+"',getDate())";
st.execute(sql);
} catch (SQLException ex) {
ex.printStackTrace();
throw new Exception("数据库错误");
}
}
public synchronized void delMsg(int msg_id) throws Exception{
try {
ResultSet rs = st.executeQuery("select * from tb_msg where msg_id='"+msg_id+"'");
if (!rs.next()) {
throw new Exception("留言不存在");
}
String sql="delete from tb_msg where msg_id='"+msg_id+"'";
st.execute(sql);
} catch (SQLException ex) {
ex.printStackTrace();
throw new Exception("数据库错误");
}
}
public synchronized WebMsg readMsg(int msg_id) throws Exception{
WebMsg result=null;
try {
ResultSet rs = st.executeQuery("select * from tb_msg where msg_id='"+msg_id+"'");
if (rs.next()) {
result=new WebMsg();
result.setMsg_id(rs.getInt("msg_id"));
result.setUserid(rs.getString("userid"));
result.setMsg(rs.getString("msg"));
result.setSend_time(rs.getDate("send_time"));
}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("数据库查询错误");
}
return result;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -