Practical JSP Advanced Programming II: The simplest DAO

Source: Internet
Author: User
Tags stmt

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;
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.