Our first example is the simplified DAO approach, which mainly introduces OOP concepts in programming.
This time, we'll make the DAO up, but still keep the simplest form for beginners to learn.
The simple DAO pattern consists of:
1 interface
2. Factory
3 Implements
4. Caller
The first example of the main program Newsdao.java code has not changed, just changed the name,
Become 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 = 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;
}
}