上一篇博客里说到用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("数据添加失败!");
}
}
}
测试之后:
可以看到面向对象的思想还是很方便的!