java & mysql 基础(三个类)

package org.zxj.Message;


public class MessageBo implements java.io.Serializable{
private String title, content;
private java.sql.Date date;
public void setTitle(String title){
this.title = title;
}
public void setContent(String content){
this.content = content;
}
public String getTitle(){
return this.title;
}
public String getContent(){
return this.content;
}
public java.sql.Date getDate(){
return this.date;
}
public void setDate(java.sql.Date date){
this.date = date;
}
}












package org.zxj.Message;


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

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/demo1";
String  USER = "root";
String PWD = "pf";
try{
Class.forName(CLASSFORNAME);
con = DriverManager.getConnection(SERVANDDB,USER,PWD);
}catch(Exception e){
e.printStackTrace();
}
}

// 该方法用来想MessageBean 传输外部数据
public void setMessage(MessageBo msg){
this.msg = msg;
}

// 该方法被jsp调用,向数据库存储信息
public void addMessage() throws Exception{
try{
PreparedStatement stm = con.prepareStatement("insert into message(title,content,messagetime) values(?,?,?)");
stm.setString(1,msg.getTitle());
stm.setString(2,msg.getContent());
stm.setDate(3,new java.sql.Date(new java.util.Date().getTime()));
try{
stm.executeUpdate();
}catch(Exception e){
}
}catch(Exception e){
}
}

//被jsp页面调用,用于获取数据
public Collection getMessage() throws Exception{
Collection ret = new ArrayList();
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 title,content,messageTime from message order by time desc");
while(result.next()){
String title = result.getString("title");
String content = result.getString("content");
java.sql.Date date = result.getDate("messageTime");
MessageBo messagebo = new MessageBo();
messagebo.setTitle(title);
messagebo.setContent(content);
messagebo.setDate(date);
ret.add(messagebo);
}
}
con.close();
}catch(Exception e){
}
return ret;
}
}











package org.zxj.Message;

import org.zxj.Message.MessageBean;
import org.zxj.Message.MessageBo;

public class test{

public static void main(String[] args) throws Exception{
MessageBo messagebo = new MessageBo();
messagebo.setTitle("abc");
messagebo.setContent("aaaaa");
messagebo.setDate(new java.sql.Date(new java.util.Date().getTime()));
MessageBean mb = new MessageBean();
mb.setMessage(messagebo);
mb.addMessage();
System.out.println("Nice");
}
}






你可能感兴趣的:(mysql)