<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" import="java.util.*" import="java.text.*" errorPage="" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>JSP中使用PreparedStatement操作資料庫</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /></head><body><table width="1002" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center"></td> </tr><% //JSP中使用PreparedStatement操作資料庫Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=SQL資料庫名"; Connection con=DriverManager.getConnection(url,"SQL使用者名稱","SQL使用者密碼"); //開啟SQL資料庫連接//插入記錄PreparedStatement myStatement1 = con.prepareStatement("insert into Article (Title,Content,UpdateIP,UpdateFrom) values (?,?,?,?)"); String UpdateIP = request.getRemoteAddr();String UpdateFrom = request.getHeader("Referer");myStatement1.setString(1,"新文章標題"); myStatement1.setString(2,"新文章內容"); myStatement1.setString(3,UpdateIP); myStatement1.setString(4,UpdateFrom); myStatement1.executeUpdate(); myStatement1.close();//精確查詢記錄PreparedStatement myStatement2 = con.prepareStatement("Select * from Article where NewsID=166"); ResultSet rs2 = myStatement2.executeQuery();while (rs2.next()) {%> <tr> <td align="center"><a href="1.jsp"><%=rs2.getString("NewsID")%></a></td> </tr> <tr> <td align="center"><%=rs2.getString("Title")%></td> </tr> <tr> <td align="left" valign="top">更新IP:<%=rs2.getString("UpdateIP")%>更新來源:<%=rs2.getString("UpdateFrom")%></td> </tr><%}myStatement2.close();//更新記錄PreparedStatement myStatement3 = con.prepareStatement("Update Article Set Title=?,Content=?,UpdateIP=?,UpdateFrom=? where NewsID=173"); myStatement3.setString(1, "新文章標題3");myStatement3.setString(2, "新文章內容3");myStatement3.setString(3, UpdateIP);myStatement3.setString(4, UpdateFrom);myStatement3.executeUpdate();myStatement3.close();//刪除記錄PreparedStatement myStatement4 = con.prepareStatement("Delete from Article where NewsID=169"); myStatement4.executeUpdate();myStatement4.close();//模糊查詢PreparedStatement myStatement5 = con.prepareStatement("Select * from Article where Title like '%' +? +'%'"); myStatement5.setString(1,"文章"); ResultSet rs5 = myStatement5.executeQuery();while (rs5.next()) {%> <tr> <td align="center"><a href="ReadNews.jsp?ID=<%=rs5.getString("NewsID")%>" target="_blank"><%=rs5.getString("Title")%></a></td> </tr> <tr> <td align="center"><%=rs5.getString("Content")%></td> </tr> <tr> <td align="left" valign="top">更新IP:<%=rs5.getString("UpdateIP")%>更新來源:<%=rs5.getString("UpdateFrom")%></td> </tr><%}myStatement5.close();con.close(); //關閉資料庫連接%> </table></body> </html>