<%@ 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>