大项目之网上书城(八)——数据库大改&添加图书
主要改动
今天也是各种各种各种出错的一天啊,经历了各种方法的重写,各种触发器的重写。
那么book表一分为n,多个子表更新数据的时候会联动book表更新数据。然后顺势写了个增加图书的方法。内容不多,错误不少、
1.数据库新增表
代码
以clothing为例,为各个类都新增了一个表。
drop table if exists `clothing`;
create table `clothing` (
`book_name` varchar(40) not null,
`price` double not null,
`describtion` varchar(200) default null,
`clazz` varchar(40) not null,
`second_id` int(11) not null auto_increment,
`book_img` blob,
`click_num` int(11) not null,
`buy_num` int(9) not null,
`re_du` int(12) default null,
`count` int(6) not null,
`is_new` int(1) not null,
`insert_date` date not null,
`book_id` int(11) default null,
primary key (`second_id`)
) engine=innodb auto_increment=5 default charset=utf8;
2.数据库新增触发器
还是以clothing表为例,两个方法,一个是当子表插入数据时,book表插入一条同样的数据,2是子表更新时,book也做出相应更新。
drop trigger if exists `c_insert`;
delimiter ;;
create trigger `c_insert` after insert on `clothing` for each row begin
insert into book(book_name,price,describtion,clazz,second_id,click_num,buy_num,count,is_new,insert_date) values(new.book_name,new.price,new.describtion,new.clazz,new.second_id,0,0,new.count,1,new.insert_date);
end
;;
delimiter ;
drop trigger if exists `c_update`;
delimiter ;;
create trigger `c_update` after update on `clothing` for each row begin
update book set book.re_du = new.click_num + new.buy_num * 100,book.click_num = new.click_num,book.buy_num = new.buy_num where clazz = new.clazz and second_id = new.second_id;
end
;;
delimiter ;
3.其他对bookservice和bookdao的修改
代码
因为改得代码太多,太乱了,不好发,于是重新都发一下实现类好了。
daoimpl
package cn.edu.bdu.mc.daos.impls;
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.sql.connection;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
import java.util.date;
import java.util.list;
import javax.sql.datasource;
import org.apache.commons.dbutils.queryrunner;
import org.apache.commons.dbutils.handlers.beanhandler;
import org.apache.commons.dbutils.handlers.beanlisthandler;
import cn.edu.bdu.mc.beans.book;
import cn.edu.bdu.mc.daos.bookdao;
import cn.edu.bdu.mc.utils.jdbcutil;
public class bookdaoimpl implements bookdao {
private datasource datasource = jdbcutil.getdatasource();
private queryrunner queryrunner = new queryrunner(datasource);
@override
public book findnewbookbypaiming(int shu) throws sqlexception {
// todo auto-generated method stub
string sql = "select * from (select * from book where is_new = 1 order by re_du desc)as book1 limit "+(shu-1)+",1";
return queryrunner.query(sql, new beanhandler(book.class));
}
@override
public list findbookremen(int page) throws sqlexception {
string sql = "select * from (select * from book order by re_du desc)as book1 limit "+(page-1)*2+",2";
return queryrunner.query(sql, new beanlisthandler(book.class));
}
@override
public void insert(book book) throws sqlexception {
// todo auto-generated method stub
string sql = "insert into "+book.getclazz()+"(book_name,price,describtion,clazz,click_num,buy_num,count,is_new,insert_date) values(?,?,?,?,0,0,?,1,?)";
queryrunner.update(sql,book.getbook_name(),book.getprice(),book.getdescribtion(),book.getclazz(),book.getcount(),new date());
}
@override
public book findbookbyid(int book_id) throws sqlexception{
string sql = "select * from book where book_id = ?";
return queryrunner.query(sql, new beanhandler(book.class),book_id);
}
@override
public listfindallbook() throws sqlexception {
string sql = "select * from book";
return queryrunner.query(sql, new beanlisthandler(book.class));
}
@override
public void deletebyid(int book_id) throws sqlexception {
string sql = "delete from book where book_id = ?";
queryrunner.update(sql,book_id);
}
@override
public void update(book book) throws sqlexception {
string sql = "update book set book_name = ?, price = ?, describtion = ?, clazz = ?, second_id = ?, click_num = ?, buy_num = ?, count = ?, is_new = ? where book_id = ?";
queryrunner.update(sql,book.getbook_name(),book.getprice(),book.getdescribtion(),book.getclazz(),book.getsecond_id(),book.getclick_num(),book.getbuy_num(),book.getcount(),book.getis_new(),book.getbook_id());
}
@override
public void addimgbyname(string book_name, string path) throws sqlexception, ioexception {
// todo auto-generated method stub
connection conn = null;
preparedstatement ps = null;
fileinputstream in = null;
in = new fileinputstream(new file(path));
conn = jdbcutil.getconn();
string sql = "update book set book_img = ? where book_name = ?";
ps = conn.preparestatement(sql);
ps.setbinarystream(1, in, in.available());
ps.setstring(2, book_name);
int count = ps.executeupdate();
if (count > 0) {
system.out.println("插入成功!");
} else {
system.out.println("插入失败!");
}
jdbcutil.release(conn, ps);
}
@override
public inputstream getimgbyid(int book_id) throws sqlexception {
// todo auto-generated method stub
connection conn = null;
preparedstatement ps = null;
resultset rs = null;
inputstream in = null;
try {
conn = jdbcutil.getconn();
string sql = "select book_img from book where book_id = ?";
ps = conn.preparestatement(sql);
ps.setint(1, book_id);
rs = ps.executequery();
while (rs.next()) {
in = rs.getbinarystream("book_img");
}
} catch (exception e) {
e.printstacktrace();
}
jdbcutil.release(conn, ps, rs);
return in;
}
@override
public book findbookbyclazzander_id(string clazz, int er_id) throws sqlexception {
// todo auto-generated method stub
string sql = "select * from "+clazz+" where second_id = ?";
book book = queryrunner.query(sql, new beanhandler(book.class),er_id);
if(book.getbook_id()==0) {
sql = "select * from book where clazz = ? and second_id = ?";
book.setbook_id(queryrunner.query(sql,new beanhandler(book.class),clazz,er_id).getbook_id());
sql = "update "+clazz+" set book_id = ?";
queryrunner.update(sql,book.getbook_id());
}
return book;
}
@override
public void updateclazz(book book) throws sqlexception {
// todo auto-generated method stub
string sql = "update "+book.getclazz()+" set book_name = ?, price = ?, describtion = ?, clazz = ?, book_id = ?, click_num = ?, buy_num = ?, count = ?, is_new = ? where second_id = ?";
queryrunner.update(sql,book.getbook_name(),book.getprice(),book.getdescribtion(),book.getclazz(),book.getbook_id(),book.getclick_num(),book.getbuy_num(),book.getcount(),book.getis_new(),book.getsecond_id());
}
}
serviceimpl
package cn.edu.bdu.mc.services.impls;
import java.io.ioexception;
import java.io.inputstream;
import java.sql.sqlexception;
import java.util.arraylist;
import java.util.list;
import javax.sql.datasource;
import cn.edu.bdu.mc.beans.book;
import cn.edu.bdu.mc.daos.bookdao;
import cn.edu.bdu.mc.daos.impls.bookdaoimpl;
import cn.edu.bdu.mc.services.bookservice;
import cn.edu.bdu.mc.utils.jdbcutil;
public class bookserviceimpl implements bookservice {
private datasource datasource = jdbcutil.getdatasource();
private bookdao dao = new bookdaoimpl();
@override
public book findnewbookbypaiming(int shu) throws sqlexception {
// todo auto-generated method stub
return dao.findnewbookbypaiming(shu);
}
@override
public void click(int book_id) throws sqlexception {
// todo auto-generated method stub
book book = dao.findbookbyid(book_id);
book.setclick_num(book.getclick_num()+1);
dao.update(book);
dao.updateclazz(book);
}
@override
public void buy(int book_id) throws sqlexception {
// todo auto-generated method stub
book book = dao.findbookbyid(book_id);
book.setbuy_num(book.getbuy_num()+1);
dao.update(book);
}
@override
public list findbookremen(int page) throws sqlexception {
return dao.findbookremen(page);
}
@override
public void addimgbyname(string book_name, string path) throws sqlexception, ioexception {
// todo auto-generated method stub
dao.addimgbyname(book_name, path);
}
@override
public inputstream getimgbyid(int book_id) throws sqlexception {
// todo auto-generated method stub
return dao.getimgbyid(book_id);
}
@override
public book findbookbyclazzander_id(string clazz, int er_id) throws sqlexception {
// todo auto-generated method stub
return dao.findbookbyclazzander_id(clazz, er_id);
}
@override
public list findbookbyclazz(string clazz) throws sqlexception {
list list = dao.findallbook();
list newlist = new arraylist<>();
//lambda表达式,emmmm,的确可读性不太好的样子。
list.foreach(book->{if(book.getclazz().equals(clazz)){newlist.add(book);}});
/*
相当于
for (book book : newlist) {
if(book.getclazz().equals(clazz)){
newlist.add(book);
}
}
*/
return newlist;
}
@override
public void insert(string book_name, double price, string describtion, string clazz, int count)
throws sqlexception {
// todo auto-generated method stub
book book = new book(book_name,price,describtion,clazz,count);
dao.insert(book);
}
}
4.addbook.jsp
代码
pageencoding="utf-8"%>
添加图书
enctype="multipart/form-data" class="form-horizontal" role="form">
书名
placeholder="请输入书名" style="float:left"/>
价格
placeholder="请输入价格" style="float:left"/>
描述
placeholder="请输入描述" style="float:left">
类别
服装
食品
网络文学
育婴童
好书拍卖
家居
运动户外
数量
placeholder="请输入数量" style="float:left"/>
图片
class="form-control input-lg btn btn-primary"style="width:100%;float:left"/>
class="form-control input-lg btn btn-warning"style="width:100%;float:left"/>
效果图
5.addnewbookservlet
代码
package cn.edu.bdu.mc.servlets;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.io.printwriter;
import java.sql.sqlexception;
import java.util.list;
import java.util.uuid;
import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.fileuploadexception;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
import cn.edu.bdu.mc.services.bookservice;
import cn.edu.bdu.mc.services.impls.bookserviceimpl;
/**
* servlet implementation class addnewbookservlet
*/
@webservlet("/addnewbook")
public class addnewbookservlet extends httpservlet {
private static final long serialversionuid = 1l;
/**
* @see httpservlet#httpservlet()
*/
public addnewbookservlet() {
super();
// todo auto-generated constructor stub
}
/**
* @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
*/
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
bookservice bookservice = new bookserviceimpl();
// string book_name = request.getparameter("book_name");
// string price = request.getparameter("price");
// string describtion = request.getparameter("describtion");
// string clazz = request.getparameter("clazz");
// string count = request.getparameter("count");
// //测试成功
// response.getwriter().write(book_name+"
"+price+"
"+describtion+"
"+clazz+"
"+count);
//把enctype="multipart/form-data"之后好像不能用普通方法获取了。。
diskfileitemfactory factory = new diskfileitemfactory();
file file = new file("d:\\target");
if(!file.exists()) {
file.mkdirs();
}
factory.setrepository(file);
servletfileupload fileupload = new servletfileupload(factory);
fileupload.setheaderencoding("utf-8");
try {
list fileitems = fileupload.parserequest(request);
string value = null;
string book_name = fileitems.get(0).getstring("utf-8");
double price = double.parsedouble(fileitems.get(1).getstring("utf-8"));
string describtion = fileitems.get(2).getstring("utf-8");
string clazz = fileitems.get(3).getstring("utf-8");
int count = integer.parseint(fileitems.get(4).getstring("utf-8"));
for (fileitem fileitem : fileitems) {
if(!fileitem.isformfield()) {
string filename = fileitem.getname();
filename = filename.substring(filename.lastindexof("\\")+1);
filename = uuid.randomuuid().tostring()+"_"+value+"_"+filename;
string webpath = "/upload/";
string filepath = getservletcontext().getrealpath(webpath+filename);
file file2 = new file(filepath);
file file3 = new file("d:\\upload\\"+filename);
file3.getparentfile().mkdirs();
file3.createnewfile();
file2.getparentfile().mkdirs();
file2.createnewfile();
inputstream inputstream = fileitem.getinputstream();
outputstream outputstream = new fileoutputstream(file2);
outputstream outputstream2 = new fileoutputstream(file3);
byte[] buffer = new byte[2048];
int len;
while((len = inputstream.read(buffer)) > 0) {
outputstream.write(buffer, 0, len);
outputstream2.write(buffer, 0, len);
}
inputstream.close();
outputstream.close();
outputstream2.close();
fileitem.delete();
try {
bookservice.insert(book_name, price, describtion, clazz, count);
string path = "d:/upload/"+filename;
bookservice.addimgbyname(book_name, path);
string htmlcode="\n" +
""
+ "
"+ ""
+ ""
+ "
"+ "
"
+"去主页\n" +
"
+ ""
+ "";
response.getwriter().write(htmlcode);
} catch (sqlexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
} catch (fileuploadexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
/**
* @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
*/
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
// todo auto-generated method stub
doget(request, response);
}
}
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!