code077.jsp
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AddBook</title>
</head>
<body>
<% request.setCharacterEncoding("utf-8"); %>
<jsp:useBean id="book" class="pack02.code075"></jsp:useBean>
<jsp:setProperty property="*" name="book"/><%-- book类与页面的input控件名称一致,才可用 --%>
<jsp:setProperty property="name" name="book" param="name"/>
<jsp:setProperty property="price" name="book" param="price"/>
<jsp:setProperty property="bookCount" name="book" param="bookCount"/>
<jsp:setProperty property="author" name="book" param="author"/>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String pwd = "mysql123";
Connection conn = DriverManager.getConnection(url,user,pwd);
String sql = "insert into tb_books(name,price,bookCount,author) values(?,?,?,?)";
PreparedStatement param = conn.prepareStatement(sql);
param.setString(1, book.getName()); //preparedStatement下标从1开始
param.setDouble(2, book.getPrice());
param.setInt(3, book.getBookCount());
param.setString(4, book.getAuthor());
int row = param.executeUpdate();
if(row > 0)
{
out.println("成功添加了" + row + "条数据");
}
param.close();
conn.close();
}
catch(Exception e)
{
out.println("图书信息添加失败");
e.printStackTrace();
}
%>
<br>
<a href="code076.jsp">返回</a>
<%--
create table tb_books (
id int auto_increment not null primary key comment '图书编号',
name varchar(45) not null comment '图书名称',
price double not null comment '价格',
bookCount int not null comment '数量',
author varchar(45) not null comment '作者'
)
--%>
</body>
</html>