DAO进阶!!

文件名:
NewsDAOMySQL.java
package news;

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

public class NewsDAOMySQL implements NewsDAO
{

Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
News news = null;
String url="jdbc:mysql://localhost:3306/joke?user=root";


public NewsDAOMySQL()
{
try {
Class.forName (
"com.mysql.jdbc.Driver");
}
catch (java.lang.ClassNotFoundException e) {
System.err.println(
"joke():"+e.getMessage());
}
}

public News getNewsByPrimaryKey(int newsid) throws SQLException
{
Connection conn=null;
Statement stmt;
ResultSet rs;
News news = null;

String sql=
"select newsid,title,content from news2"+
" where newsid="+newsid+"";
conn = getConnection();
stmt = conn.createStatement();
rs=stmt.executeQuery(sql);

if(rs.next())
{
news = new News(rs.getInt(1), rs.getString(2),rs.getString(3));
}
rs.close();
stmt.close();
conn.close();
return news;
}

private Connection getConnection() throws SQLException
{
Connection conn = null;
conn = DriverManager.getConnection(url);
return conn;
}

public News[] getAllNews() throws SQLException
{

String sql=
"select newsid,title,content from news2";
conn = getConnection();
stmt = conn.createStatement();
rs=stmt.executeQuery(sql);

List list = new ArrayList();
while(rs.next())
{
list.add(new News(rs.getInt(1), rs.getString(2),rs.getString(3)));
}
conn.close();
if(list.size() == 0) return null;
News[] news = new News[list.size()];
return (News[])list.toArray(news);

}

}
文件名:NewsDAO
package news;

import java.sql.SQLException;

public interface NewsDAO {

public News getNewsByPrimaryKey(int newsid) throws SQLException;
public News[] getAllNews() throws SQLException;
}
文件名:
NewsDAOFactory.java
package news;


public class NewsDAOFactory {


public static NewsDAO getDAO() throws Exception {

NewsDAO newsDao = null;
String className =
"news.NewsDAOMySQL";
try {
newsDao = (NewsDAO) Class.forName(className).newInstance();
}
catch (Exception se) {
}
return newsDao;
}
}
调用文件名:
getAllNews.jsp
<%@page contentType=
"text/html;charset=gb2312" %>
<%@page import=
"news.*" %>
<%

NewsDAO newsDao = NewsDAOFactory.getDAO();
News[] news = newsDao.getAllNews();
if(news != null) {
for(int i=0;i<news.length;i++)
{ out.println(
"Newsid1:"+news<i>.getNewsid());
out.println(
"<br>");
out.println(
"Title:"+news<i>.getTitle());
out.println(
"<br>");
out.println(
"Body:"+news<i>.getContent());
}
}
else out.println(
"Failed.");
%>

lunzi   2004-12-21 21:05:11 评论:0   阅读:1012   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2004-2010 powered by YuLog