使用动态数据进行数据库内容的增删改查操作有两种方法:
在此定义数据库连接为conn
假设有表单进行数据输入并提交到处理页面
一种是使用预编译格式:
其格式如下:
String name = request.getParameter("name");//获取前页表单中name为name的值 String password = request.getParameter("password");//获取前页表单中name为password的值 String sql = "insert into user values(null,?,?)";//定义数据库操作语句 PreparedStatement pst = conn.prepareStatement(sql);//创建预编译对象 pst.setString(1,name);//为第一个?赋值,将表单获取的name值赋给第一个? pst.setString(2,password);//为第二个?赋值,将表单获取的password值赋给第二个? pst.executeUpdate();//执行数据插入操作
二种是使用普通格式:
其格式如下:
String name = request.getParameter("name");//获取前页表单中name为name的值 String password = request.getParameter("password");//获取前页表单中name为password的值 String sql = "insert into user values(null,'" + name + "','" + password + "')";//定义数据库操作语句 Statement state = conn.createStatement();//创建Statement对象 state.executeUpdate(sql);//执行数据插入操作
具体代码如下:
表单页面:form.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <form action="preparedStatement_test.jsp" method = "get"> <input type = "text" name = "name" /> <input type = "password" name = "password" /> <input type = "submit" /> </form> </body> </html>
数据处理页面:preparedStatement_test.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <% String url = "jdbc:mysql://localhost:3306/javaweb"; String root = "root"; String pass = "123456"; Connection conn = null; try{ //指定数据库驱动文件 Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url,root,pass); }catch(ClassNotFoundException cnfe){ out.print("找不到驱动器文件!"); }catch(SQLException se){ out.print("数据库连接失败!"); } %> <% String name = request.getParameter("name"); String password = request.getParameter("password"); String sql = "insert into user values(null,?,?)"; PreparedStatement pst = null; try{ pst = conn.prepareStatement(sql); pst.setString(1,name); pst.setString(2,password); pst.executeUpdate(); out.print("数据保存成功!"); }catch(SQLException se){ out.print("添加数据出错!"); } %> <% //从服务器取出数据并显示 String sql1 = "select * from user where name = ?"; pst = conn.prepareStatement(sql1); pst.setString(1,name); ResultSet rs = pst.executeQuery(); out.print("<table><tr><td colspan = '3'>您的数据</td></tr>"); out.print("<tr><td>id</td><td>name</td><td>password</td></tr>"); while(rs.next()){ out.print("<tr><td>" + rs.getInt(1) + "</td><td>" + rs.getString(2) + "</td><td>" + rs.getString(3) + "</td></tr>"); } out.print("</table>"); %> </body> </html>