java+javabean 连接数据库 写数据 读数据

这是一个案例BBS留言板

首先建表



写一个表示留言数据的javabean 


写一个执行数据库操作的javaben 

public class MessageBean {
private Connection con;
MessageBO msg;
public MessageBean(){
String CLASSFORNAME="com.mysql.jdbc.Driver";
String SERVANDDB="jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=UTF-8 ";
String USER="root";
String PWD="";
try {
Class.forName(CLASSFORNAME);
con=(Connection) DriverManager.getConnection(SERVANDDB, USER, PWD);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setMessage(MessageBO msg){
this.msg=msg;
}

public void addMessage()throws Exception{
//response.setContentType("text/html; charset=utf-8");
try {
PreparedStatement stm= con.prepareStatement("insert into message values(?,?,?,?,?)");
   stm.setString(1, msg.getTitle());
   stm.setString(2, msg.getName());
   
   System.out.println(msg.getName());
   
   if(msg.getEmail().length()==0){
    stm.setString(3, null);
   }else{
    stm.setString(3, msg.getEmail());
   }
   stm.setString(4, msg.getContent());
   stm.setDate(5, new java.sql.Date(new java.util.Date().getTime()));
   System.out.println(new java.util.Date().getTime());
   stm.executeUpdate();
   con.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public Collection<MessageBO> getMessage()throws Exception{
Collection<MessageBO> ret=new ArrayList<MessageBO>();
try {
Statement stm=con.createStatement();
ResultSet result=stm.executeQuery("select count(*) from message");
int message_count=0;
if(result.next()){
message_count=result.getInt(1);
result.close();
}
if(message_count>0){
result=stm.executeQuery("select * from message order by date desc");
while(result.next()){
String title=result.getString("title");
String name=result.getString("name");
String mail=result.getString("email");
String content=result.getString("content");
java.sql.Date date=result.getDate("date");
MessageBO message=new MessageBO();
message.setName(name);
message.setTitle(title);
message.setContent(content);
message.setEmail(mail);
message.setDate(date);
ret.add(message);
}
result.close();
stm.close();
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}

return ret;
}
}


写一个填写留言的界面  


写一个处理添加留言的jsp页面

<%try{
  messageBean.setMessage(messageBO);
  messageBean.addMessage();
   }catch(Exception e){
  e.printStackTrace();
   }%>
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>add message into table</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
  </head>
  
 <body>
  
   <jsp:forward page="viewMessage1.jsp"/></body>
   </body>
</html>

最后写一个显示查看留言的jsp页面


到此处功能结束。要源码可以到我空间下载。问题是我的数据库现在还是中文显示乱码。新手嘿嘿

你可能感兴趣的:(java,Web)