1. 程式人生 > >JDBC(三)——使用Statement介面對資料庫實現增刪改操作(2)

JDBC(三)——使用Statement介面對資料庫實現增刪改操作(2)

上一篇部落格裡說到用Statement介面對資料庫實現增刪改操作,其中的sql語句是我們直接手寫的;

但在實際開發過程中,資料都是從前臺直接獲取的,而不是自己手動匯入的;

1.在新增圖書這個操作中,我們可以寫一個新增方法:

//增加圖書的方法
	private static int addBook(int id,String bookName,double price,String author,int bookTypeId) throws Exception{
		//引用工具類dbUtil
		DbUtil dbUtil=new DbUtil();
		//連線資料庫
		Connection con=dbUtil.getCon();
		//獲取Statement介面
		Statement stmt=con.createStatement();
		//sql語句
		String sql="insert into t_book values("+id+",'"+bookName+"',"+price+",'"+author+"',"+bookTypeId+")";
		//執行sql語句
		int result=stmt.executeUpdate(sql);
		//關閉資料庫,將關閉的方法封裝到工具類裡面的close()方法裡面
		dbUtil.close(stmt, con);
		return result;
	}

這樣的sql語句就可以用匯入的資料,在進行測試之後:

public static void main(String[] args) throws Exception {
		int result=addBook(5,"Web前端",63.0,"大牛",3);
		if(result==1){
			System.out.println("資料新增成功!");
		}else{
			System.out.println("資料新增失敗!");
		}
	}

結果:

 

2.但是這樣其實也並不好,我們可以用面向物件思想來寫一個Model類,將書籍的各個屬性進行封裝成一個Book類;

package Month01.Day08.Model;

public class Book {

	private int id;
	private String bookName;
	private float price;
	private String author;
	private int bookTypeId;
	
	public Book(int id, String bookName, float price, String author, int bookTypeId) {
		super();
		this.id = id;
		this.bookName = bookName;
		this.price = price;
		this.author = author;
		this.bookTypeId = bookTypeId;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public int getBookTypeId() {
		return bookTypeId;
	}
	public void setBookTypeId(int bookTypeId) {
		this.bookTypeId = bookTypeId;
	}
	
}

然後再寫addBook2()方法:

package Month01.Day08.Demo01;

import java.sql.Connection;
import java.sql.Statement;

import Month01.Day08.DbUtil.DbUtil;
import Month01.Day08.Model.Book;

public class insert_sql_2 {

	//增加圖書的方法
	private static int addBook2(Book book) throws Exception{
		DbUtil dbUtil=new DbUtil();
		Connection con=dbUtil.getCon();
		Statement stmt=con.createStatement();
		String sql="insert into t_book values("+book.getId()+",'"+book.getBookName()+"',"+
					book.getPrice()+",'"+book.getAuthor()+"',"+book.getBookTypeId()+")";
		int result=stmt.executeUpdate(sql);
		return result;
	}
	

	public static void main(String[] args) throws Exception {
		Book book=new Book(6,"Java設計思想",45,"亨得利",4);
		int result=addBook2(book);
		if(result==1){
			System.out.println("資料新增成功!");
		}else{
			System.out.println("資料新增失敗!");
		}
	}
}

測試之後:

可以看到面向物件的思想還是很方便的!