標籤:
使用動態資料進行資料庫內容的增刪改查操作有兩種方法:
在此定義資料庫連接為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>
jsp中使用動態資料進行mySQL資料庫的兩種操作方法