MVC表述
MVC 是(Model View Controller)模型-视图-控制器设计创建 Web 应用程序的模式
------ 1.模型对象负责在数据库中存取数据,相当与传输数据的载体。(javaBean)
------ 2.视图是用户看到并与之交互的界面,它只是作为一种输出数据并允许用户操纵的方式。(jsp、html)
------ 3.控制器负责从视图读取数据,控制用户输入,并向模型发送数据(servlet)
实现JDBC增删查改操作
Book类
package com.qyx;
public class Book {
private int id;
private String bookName;
private int price;
private String description;
public Book(){
}
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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
DBUtil类
package com.qyx;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
String url="jdbc:mysql://localhost:3306/test";
String username="root";
String password="123456";
private Connection conn;
public DBUtil(){
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//增
public void insert(int id,String bookName,int price,String description){
String insert="insert into book(id,bookName,price,description) values(?,?,?,?)";
try {
PreparedStatement pst=this.conn.prepareStatement(insert);
pst.setInt(1, id);
pst.setString(2,bookName);
pst.setInt(3, price);
pst.setString(4, description);
pst.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//删
public void delete(int id){
String delete="delete from book where id=? ";
try {
PreparedStatement pst=this.conn.prepareStatement(delete);
pst.setInt(1, id);
pst.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//查
public void inquiry(String bookName){
String inquiry="select * from book where bookName=?";
try {
PreparedStatement pst=this.conn.prepareStatement(inquiry);
pst.setString(1,bookName);
pst.execute();
ResultSet rt=pst.getResultSet();
while(rt.next()){
for(int i=1;i<=4;i++){
String mess=rt.getString(i);
System.out.print(mess+" ");
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//改
public void change(int price,String bookName){
String update="update book set price=? where bookName=?";
try {
PreparedStatement pst=this.conn.prepareStatement(update);
pst.setInt(1, price);
pst.setString(2, bookName);
pst.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]){
DBUtil dl=new DBUtil();
// dl.insert(1, "nihao",55, "hahah");
// dl.delete(1);
dl.inquiry("nihao");
// dl.change(60, "nihao");
}
}