JDBC achieve simple CRUD (single table)

0. preparations

Development tools: MySQL database, intelliJ IDEA2017.

Preparation jar package: mysql-connector-java-5.1.28-bin.jar (others available)

1. Database Data Preparation

2. Project structure diagram

3. Code

Entity class Book.java

package com.zzuli.entity;

import java.util.Date;

/**
 *
 * Books entity class
 * Created by hejjon on 2019/5/25.
 */
public class Book {
    private int id;
    private String bookName;
    private String author;
    private Date pubDate;           // 出版日期 util.Date


    public Book() {
    }

    public Book(int id, String bookName, String author, Date pubDate) {
        this.id = id;
        this.bookName = bookName;
        this.author = author;
        this.pubDate = pubDate;
    }

    public Book(String bookName, String author, Date pubDate) {
        this.bookName = bookName;
        this.author = author;
        this.pubDate = pubDate;
    }

    public int getId() {
        return id;
    }

    public String getBookName() {
        return bookName;
    }

    public String getAuthor() {
        return author;
    }

    public Date getPubDate() {
        return pubDate;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

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

    public void setPubDate(Date pubDate) {
        this.pubDate = pubDate;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bookName='" + bookName + '\'' +
                ", author='" + author + '\'' +
                ", pubDate=" + pubDate +
                '}';
    }
}

Dao layer interface BookDao.java

Package Penalty for com.zzuli.dao;

import com.zzuli.entity.Book;

import java.util.List;

/**
 * Created by hejjon on 2019/5/25.
 * / 
Public  interface BookDao {

    /**
     * Add books
     * @Param book book objects to be added
     * @return
     */
    int insertBook(Book book);

    /**
     * Remove the specified id books
     * @Param id you want to remove the book id
     * @return
     */
    int deleteBook(int id);

    /**
     * Modify the Book
     * @Param after the book edit book
     * @return
     */
    int updateBook(Book book);

    /**
     * Find specify the title of the book
     * @param bookName
     * @return
     */
    Book selectBookByName(String bookName);

    List<Book> selectAllBook();
}

Dao layer implementation class: BookDaoImpl.java

package com.zzuli.dao.impl;

import com.zzuli.dao.BookDao;
import com.zzuli.entity.Book;

import java.sql.*; import java.util.ArrayList; import java.util.List; /** * Created by hejjon on 2019/5/25. */ public class BookDaoImpl implements BookDao { private final String jdbcDriver = "com.mysql.jdbc.Driver"; private final String url = "jdbc:mysql://localhost:3306/db_book"; private final String userName = "root"; private final String password = "123123"; @Override public int insertBook(Book book) { int n = 0; String sql = "insert into t_book values (default,?,?,?)"; Connection conn = null; PreparedStatement ps = null; the pubDate a java.sql.Date = null ; the try { // load drive the Class.forName (jdbcDriver); // Get connected Conn = the DriverManager.getConnection (URL, the userName, password); // Create Session PS = conn.prepareStatement (SQL ); // ? value set ps.setString (1 , book.getBookName ()); ps.setString(2, book.getAuthor()); pubDate = new java.sql.Date(book.getPubDate().getTime()); ps.setDate(3, pubDate); // 执行sql n = ps.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } The finally { // Close resource database the try { IF ( null ! = PS) { ps.close(); } } catch (SQLException e) { e.printStackTrace (); } try { if (null != conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace (); } } return n; } @Override public int deleteBook(int id) { String sql = "delete from t_book where id=?"; int n = 0; Connection conn = null; PreparedStatement ps = null; the try { // load drive the Class.forName (jdbcDriver); // Get connected Conn = the DriverManager.getConnection (URL, the userName, password); // Create a session ps = conn.prepareStatement (SQL); // ? set value ps .setInt (. 1 , ID); // execute SQL n-= ps.executeUpdate (); } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } finally { try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace (); } try { if (null != conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace (); } } return n; } @Override public int updateBook(Book book) { String sql = "update t_book set bookName=?, author=?, pubDate=? where id=?"; int n = 0; Connection conn = null; PS the PreparedStatement = null ; the try { // load drive the Class.forName (jdbcDriver); // Get connected Conn = the DriverManager.getConnection (URL, the userName, password); // Create Session PS = conn.prepareStatement (SQL); ps.setString(1, book.getBookName()); ps.setString(2, book.getAuthor()); ps.setDate(3, new java.sql.Date(book.getPubDate().getTime())); ps.setInt(4, book.getId()); n = ps.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } finally { try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace (); } try { if (null != conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace (); } } return n; } @Override public Book selectBookByName(String bookName) { String sql = "select * from t_book where bookName=?"; Book book = null; Connection conn = null; PreparedStatement ps = null; RS the ResultSet = null ; the try { // load drive the Class.forName (jdbcDriver); // Get connected Conn = the DriverManager.getConnection (URL, the userName, password); // Create Session PS = conn.prepareStatement (SQL); ps.setString(1, bookName); rs = ps.executeQuery(); if (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("bookName"); String author = rs.getString("author"); java.util.Date pubDate = rs.getDate("pubDate"); book = new Book(id, name, author, pubDate); } } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } finally { try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace (); } try { if (null != conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace (); } } return book; } @Override public List<Book> selectAllBook() { String sql = "select * from t_book"; List<Book> list = new ArrayList<>(); Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; the try { // load drive the Class.forName (jdbcDriver); // Get connected Conn = the DriverManager.getConnection (URL, the userName, password); // Create Session PS = conn.prepareStatement (SQL); // Get the result set rs = ps.executeQuery (); // traverse the result set the while (rs.next ()) { int ID = rs.getInt ( "ID" ); String bookName = rs.getString("bookName"); String author = rs.getString("author"); Date pubDate = rs.getDate("pubDate"); Book book = new Book(id, bookName, author, pubDate); list.add(book); } } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } finally { try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace (); } try { if (null != conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace (); } } return list; } }

Test categories: Test.java

package com.zzuli.test;

import com.zzuli.dao.BookDao;
import com.zzuli.dao.impl.BookDaoImpl;
import com.zzuli.entity.Book;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Test class
 * Created by hejjon on 2019/5/25.
 */
public class Test {
    public static void main(String[] args) {
        // testInsert();
        //  testDelete();
        // sestUpdate();
        // testSelect();

        testSelectAllBook();

    }

    private static void testSelectAllBook() {
        BookDao bookDao = new BookDaoImpl();

        List<Book> list = new ArrayList<>();

        list = bookDao.selectAllBook();

        for (Book book : list) {
            System.out.println(book);
        }
    }

    // Test for books by title 
    public  static  void testSelect () {
        BookDao bookDao = new BookDaoImpl();
        Book Book = bookDao.selectBookByName ( "Journey" );

        System.out.println(book);
    }

    // Test Method Books modified 
    public  static  void testUpdate () {
         // create an object class that implements layer dao 
        BookDao bookDao = new new BookDaoImpl ();
        String dateStr = "1788-06-15";
        Date pubDate = null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            pubDate = df.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace ();
        }

        Book Book = new new Book (2 "Journey to the West", "WuChengEn" , the pubDate);

        int i = bookDao.updateBook(book);

        if (i > 0) {
            System.out.println ( "Book modified successfully" );
        } else {
            System.out.println ( "Book modification failed" );
        }
    }


    // test method to delete books 
    public  static  void TestDelete () {
        BookDao bookDao = new BookDaoImpl();
        int i = bookDao.deleteBook(5);

        if (i > 0) {
            System.out.println ( "successfully remove a book" );
        } else {
            System.out.println ( "Delete Book failed" );
        }
    }


    // Test Method Books add 
    public  static  void testInsert () {
         // create an object class that implements layer dao 
        BookDao bookDao = new new BookDaoImpl ();
        String dateStr = "1678-09-24";
        Date pubDate = null;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            pubDate = df.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace ();
        }

        Book Book = new new Book ( "Deer", "Joe Smith" , the pubDate);

        int i = bookDao.insertBook(book);

        if (i > 0) {
            System.out.println ( "Book added successfully" );
        } else {
            System.out.println ( "Book Add failed" );
        }
    }
}

4. Summary:

java.sql.Date, conversion between java.util.Date, String:
// String ---> java.util.Date       parse()方法
String DateStr = "1997-02-24";
Date date = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
date = df.parse(DateStr);
} catch (ParseException e) {
e.printStackTrace();
}

// java.util.Date ---> String format()方法
System.out.println(df.format(date)); // 1997-02-24


System.out.println(System.currentTimeMillis()); // 1558864421743

// java.util.Date ---> java.sql.Date
java.util.Date utilDate = new java.util.Date(1558864204513L); // 是long类型 L别丢了

java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println(utilDate); // Sun May 26 17:50:04 CST 2019
System.out.println(sqlDate); // 2019-05-26
 
 
 

 

Guess you like

Origin www.cnblogs.com/hejjon/p/10926827.html