execute()方法应该仅在语句能返回多个ResultSet对象,多个更新计数或ResultSet对象与更新计数的组合时使用。
testExecute.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <%@page import="java.sql.*" %> <%request.setCharacterEncoding("UTF-8"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>无敌超官网-你值得拥有</title> <style type="text/css"> a:hover{color:red;} </style> </head> <body> SQL语句<br> <% String sql=request.getParameter("content");//获取文本区的内容 if(sql==null){ %> <form action="mysql/testExecute.jsp" method="post"> <p><input type="text" name="content" size="40" required maxlength="40"/></p> <p><input type="submit" value="提交"> </form> <% } else{ String url="jdbc:mysql://localhost:3306/student?useSSL=true"; String useName="root"; String password="2277092"; Connection conn=null; Statement stmt=null;//向数据库发送SQL语句,其对象用conn.createStatement()创建, //返回的结果存放在ResultSet对象中 try{ Class.forName("com.mysql.jdbc.Driver"); out.print("加载驱动类成功<br>"); } catch(Exception e){ out.print("加载驱动类出现异常"); } try{ conn=DriverManager.getConnection(url,useName,password); stmt=conn.createStatement(); out.print("执行的SQL语句为:"+sql); //execute()用法 //使用execute()执行未知的语句,如果sql是正确的语句,则返回true,否则返回false boolean isResultSet=stmt.execute(sql); int count=0; while(true){ count++; if(isResultSet){ ResultSet rs=stmt.getResultSet(); out.print("返回的执行结果 "+count+" 为结果集<br>"); //显示返回的结果集 while(rs.next()){ //注意MySQL里面INT(10),如果数字很长,就用long Long no=rs.getLong(1); String name=rs.getString(2); String phone=rs.getString(3); out.print(no+" "+name+" "+phone+"<br>"); } rs.close(); } else{ int affectdRowCount=stmt.getUpdateCount(); if(affectdRowCount==-1)break; out.print("返回的执行结果 "+count+" 为更新计数<br>"); out.print("<br>"); } //使用execute()方法时需要调用getMoreResus()方法 isResultSet=stmt.getMoreResults(); } stmt.close(); } catch(Exception e){ out.print("出现SQLExcepion异常"); } finally{ try{ if(conn!=null){ conn.close(); out.print("<br><a href=‘mysql/testExecute.jsp‘>重新输入SQL语句</a>"); } } catch(Exception e){ out.print("关闭数据库连接时出现异常"); } } } %> </body> </html>
时间: 2024-09-28 16:10:15