我們的第一個例子是簡化的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;
}
}