jsp中怎么实现按下一个按钮后执行一条sql语句
2个回答
展开全部
jsp页面相关代码:
<form action="/servlet/RegServlet">
<input type="submit" value="点击该按钮执行sql语句">
</form>
web.xml文件:
<servlet>
<servlet-name>RegServlet</servlet-name>
<servlet-class>com.servlet.RegServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegServlet</servlet-name>
<url-pattern>/servlet/RegServlet</url-pattern>
</servlet-mapping>
java代码:
public class RegServlet extends HttpServlet {
public RegServlet(){
super();
}
public void destroy(){
super.destroy();
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doPost(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
// 调用jdbc
Connection conn = null; //声明一个Connection对象,用来连接数据库
PreparedStatement pstmt = null; //声明PreparedStatement对象,用来向数据库插入数据条数据
try {
//连接到MySQL数据库中的bank数据库模式
Class.forName("com.mysql.jdbc.Driver");
System.out.println("创建驱动成功!");
//连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "1234");
System.out.println("连接数据库成功!");
//插入数据的SQL语句
String sql = "INSERT INTO dept(id,d_name) VALUES(?,?)";
pstmt = conn.prepareStatement(sql);
//设置插入数据的顺序
pstmt.setString(1, “id”);
pstmt.setString(2, “name”);
int result = pstmt.executeUpdate();
//判断执行结果
if (result == 1) {
out.print("插入数据成功!");
}else {
out.print("插入数据失败!请重新插入!");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
out.close();
}
public void init()throws ServletException{
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询