在home.jsp中查询数据库信息
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/book"; Connection connection= (Connection) DriverManager.getConnection(url,"root","root"); Statement stmt=connection.createStatement(); //stmt.executeQuery(sql);//执行查询的函数 返回结果集 String sql="select * from user"; ResultSet rs =stmt.executeQuery(sql); while(rs.next()){ out.print(rs.getString("username")+"-"+rs.getString(3)+"<br>"); } %> </body> </html>使用PreparedStatement执行sql语句
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/book"; Connection connection= (Connection) DriverManager.getConnection(url,"root","root"); String sql="select*from user where username=? and password=?"; PreparedStatement ps=connection.prepareStatement(sql); ps.setString(1,request.getParameter("username")); ps.setString(2,request.getParameter("password")); //String sql="insert into user(username,password,gender) values(?,?,?)"; ResultSet rs= ps.executeQuery(); while(rs.next()){ out.print(rs.getString("username")+"-"+rs.getString(3)+"<br>"); } /* Statement stmt=connection.createStatement(); //stmt.executeQuery(sql);//执行查询的函数 返回结果集 String sql="select * from user"; ResultSet rs =stmt.executeQuery(sql); while(rs.next()){ out.print(rs.getString("username")+"-"+rs.getString(3)+"<br>"); } */ %> </body> </html>