Java JDBC实训----CMS系统

注意:三个工具包使用才能JDBCUtils

  • commons-dbcp-1.4.jar
  • mysql-connector-java-5.1.47.jar
  • commons-pool-1.6.jar

   话不多说,直接上代码

阶段1:创建数据库表news

CREATE TABLE `cms`.`CMS`(  
   `title` VARCHAR(100) NOT NULL COMMENT '标题', 
    `author` VARCHAR(20) NOT NULL COMMENT '作者',  
   `TIME` VARCHAR(40) NOT NULL COMMENT '时间', 
    `content` TEXT NOT NULL COMMENT '内容', 
);

创建News表类


import java.sql.Time;

public class News {
    private String title;
    private String author;
    private String time;
    private String content;

    public News() {
    }

    public News(String title, String author, String time, String content) {
        this.title = title;
        this.author = author;
        this.time = time;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
    @Override
    public String toString() {
        return "News{" +
                "title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", time='" + time + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

阶段2:创建HTML模板文件

创建一个文本文件,重命名为news.template   打开输入代码

<head>
     <title>{title}</title>
</head>
<body>
<table align=”center” width=”95%” border=”1”>
  <tr>
       <td width=”10%”><b>标题:</b></td>
       <td>{title}</td>
</tr>
<tr>
<td width=”10%”><b>作者:</b></td>
<td>{author}</td>
</tr>
<tr>
     <td width=”10%”><b>时间:</b></td>
     <td>{createTime}</td>
</tr>
<tr>
     <td width=”10%”><b>内容:</b></td>
     <td>{content}</td>
</tr>
 </table>
</body>

阶段3:从数据库读取新闻信息,保存在泛型集合中

要求:

  采用DAO模式,创建NewsDao接口及NewsDaoSQLServerImpl实现类,完成新闻信息的读取。还需要创建实体类News来存储和传输数据,创建数据库连接和关闭工具类BaseDao来简化DAO的操作,避免代码重复。

接口:

import Table.News;

import java.util.ArrayList;

public interface NewsDao {
        /*
         * 保存新闻信息内容
         */
        public String seve(News news) ;
        /*

         */
        ArrayList<News> findAll();
    }

实现类:

import Table.News;
import Utils.JDBCUtils;
import java.sql.*;
import java.util.ArrayList;
public class NewsDao implements Interface.NewsDao {
    @Override
    public String seve(News news)  {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            connection= JDBCUtils.getConnection();
            preparedStatement=connection.prepareStatement("INSERT INTO cms.news (title,author,TIME,content) VALUES (?,?,?,?);");
            preparedStatement.setString(1,news.getTitle());
            preparedStatement.setString(2, news.getAuthor());
            preparedStatement.setString(3,  news.getTime());
            preparedStatement.setString(4, news.getContent());
            preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            JDBCUtils.realease(resultSet,preparedStatement,connection);
        }
        return null;
    }
    //查询数据库所有新闻信息
    @Override
    public ArrayList<News> findAll() {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            connection=JDBCUtils.getConnection();
            preparedStatement=connection.prepareStatement("select * from news ");

            resultSet=preparedStatement.executeQuery();
            //将新闻信息保存在ArrayLIst集合
            ArrayList<News> newslist=new ArrayList<News>();
            while(resultSet.next()){
                News news=new News();
                news.setTitle(resultSet.getString("title"));
                news.setAuthor(resultSet.getString("author"));
                news.setTime(resultSet.getString("time"));
                news.setContent(resultSet.getString("content"));
                newslist.add(news);
            }
            //返回集合
            return newslist;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtils.realease(resultSet, preparedStatement, connection);
        }
        return null;
    }
}

阶段4:读取模板文件

 利用IO流读取模板文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
public class FileIO {
    public String readFile(String a) throws Exception{
        Reader reader= new InputStreamReader(new FileInputStream(a), "utf-8");
        char[] bytes = new char[1024];  //设定一个数组,俺数组数读取,提高效率;
        String templatestr = "";
        int readlen = 0;
        while((readlen=reader.read(bytes))!=-1) {
            templatestr = new String(bytes, 0, readlen);  //读取从0到readlen的值
        }
        reader.close();
        return templatestr;
    }
    public void writeFile(String filePath, String replacestr) throws Exception {
        File file = new File(filePath);
        if(!file.exists())file.createNewFile();
        Writer writer = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
        writer.write(replacestr);
        writer.flush();
        writer.close();
    }
}

阶段5:编写生成HTML文件的方法

import java.util.ArrayList;
import DaoSQLServerImPlace.NewsDao;
import FileIO.FileIO;
import Table.News;
/**
 *使用数据库内容替换模板文件,生成HTML文件
 *@author屈先森
 */
public  class TOHtml {
    public static void toHtml() throws Exception {
        //1.读取模板文件内容,返回文件内容字符串
        FileIO fileio=new FileIO();
        //模板文件的存放位置
        String templatestr= fileio.readFile("D:/桌面/news.template");
        //2.读取数据库表,获取新闻列表
        NewsDao newsDaoSQLServerImplement=new NewsDao();
        ArrayList<News> newsList=newsDaoSQLServerImplement.findAll();
        //3.替换模板文件,为每一条新闻创建一个HTML文件来显示其信息
        for(int i=0;i<newsList.size();i++){
            //3.1获取一条新闻
            News news=newsList.get(i);
            //3.2使用该条新闻信息替换对应占位符
            String replacestr=new String();
            replacestr=templatestr;
            replacestr= replacestr.replace("{title}",news.getTitle());
            replacestr=replacestr.replace("{author}",news.getAuthor());
            replacestr=replacestr.replace("{createTime}",  news.getTime().toString());
            replacestr=replacestr.replace("{content}",news.getContent());
            //3.3为该条新闻生成HTML文件,生成网页文件地址由自己决定
            String filePath="D:/桌面/CMS"+i+".html";
            fileio.writeFile(filePath, replacestr);
        }
    }
}

阶段5:测试类,插入新闻,生成网页方法

import DaoSQLServerImPlace.NewsDao;
import Table.News;

import java.util.Scanner;
public class Test {
    //实现插入新闻数据功能和调用生成网页方法
    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);
        NewsDao cmsInterface = new NewsDao();
        while (true) {
            System.out.println("请按照提示选择以下功能:\n" + "输入新闻信息请按1\n"+"生成网页请按2\n"+ "退出请按0\n");
            String number = input.next();
            if (number.equals("1")) {
                System.out.println("请输入标题:");
                String title = input.next();
                System.out.println("请输入作者");
                String author = input.next();
                System.out.println("请输入时间:");
                String time = input.next();
                System.out.println("请输入内容:");
                String content = input.next();

                News news = new News();
                news.setTitle(title);
                news.setAuthor(author);
                news.setTime(time);
                news.setContent(content);

                cmsInterface.seve(news);
                System.out.println("=====内容输入成功!=====\n");
            }
            if (number.equals("2")){
                TOHtml.toHtml();
                System.out.println("=====生成网页成功!====");
            }
            if (number.equals("0")){
                System.exit(0);
            }
        }
    }
}

最重要的JDBCUtils工具类不要忘记!!!

一定需要三个工具包使用才能JDBCUtils!!!!

  • commons-dbcp-1.4.jar
  • mysql-connector-java-5.1.47.jar
  • commons-pool-1.6.jar
package Utils;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCUtils {
    ///DataSource 提高
    private static DataSource dataSource = null;

    static {
        try {
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties"); //加载配置文件
            Properties properties = new Properties();
            properties.load(in);
            //创建数据源  工厂模式-->创建
            dataSource = BasicDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //获取链接
    public static Connection getConnection() throws Exception {
        return dataSource.getConnection();
    }


    //释放资源
    public static void realease(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection){
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            resultSet=null;
        }
        if(preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            preparedStatement=null;
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            connection=null;
        }
    }
}

  • 9
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程粘仁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值