JSP中使用JDBC操作数据库
实体类,Book.java:
package com.home.web.dto;
public class Book {
private int id;
private String name;
private double price;
private int bookCount;
private String author;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getBookCount() {
return bookCount;
}
public void setBookCount(int bookCount) {
this.bookCount = bookCount;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
index.jsp:
用于放置添加图书信息所需要的表单
<%@page import="java.net.URLDecoder"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>添加图书</title> </head> <body> <form action="result.jsp" method="post" onsubmit="return check(this);"> <table align="center" width="450"> <tr> <td align="center" colspan="2"> <h2>添加图书信息</h2> </td> </tr> <tr> <td align="right">图书名称:</td> <td><input type="text" name="name" /></td> </tr> <tr> <td align="right">价 格:</td> <td><input type="text" name="price" /></td> </tr> <tr> <td align="right">数 量:</td> <td><input type="text" name="bookCount" /></td> </tr> <tr> <td align="right">作 者:</td> <td><input type="text" name="author" /></td> </tr> <tr> <td align="center" colspan="2"><input type="submit" value="添 加" /></td> </tr> </table> </form> </body> </html>
result.jsp:
<%@page import="java.sql.*"%>
<%@ page language="java" import="java.util.*" autoFlush="true"
import="com.home.web.mamager.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
%>
<jsp:useBean id="book" class="com.home.web.dto.Book"></jsp:useBean>
<jsp:setProperty property="*" name="book" />
<%
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/test";
Connection conn=DriverManager.getConnection(url,"root","123456");
String sql="insert into t_books(name,price,bookCount,author)values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, book.getName());
ps.setDouble(2, book.getPrice());
ps.setInt(3, book.getBookCount());
ps.setString(4, book.getAuthor());
int row=ps.executeUpdate();
if(row>0){
out.print("成功添加了"+row+"条数据!");
}
ps.close();
conn.close();
} catch (Exception e) {
out.print("图书信息添加失败!");
e.printStackTrace();
}
%>
<br>
<a href="index.jsp">返回</a>
</body>
</html>
