Welcome

首页 / 网页编程 / JSP / 实战JSP进阶编程之二:最简单的DAO

实战JSP进阶编程之二:最简单的DAO2011-08-21我们的第一个例子是简化的DAO方式,主要是在编程中引入了oop概念。

这次,我们将DAO补齐,但仍然保持最简单的形式,以便初学者学习。

简单的DAO模式构成:

1 interface

2. Factory

3 Implements

4. caller

第一个例子中的主程序NewsDAO.java代码没有改动,只是改了个名字,

成为implements.

package news;
import java.sql.*;
public class NewsDAOMySQL implements NewsDAO
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = 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;
}
}