数据查询的方法
2018-08-19 本文已影响0人
神坛下的我
Util.java
import java.sql.*;
public class Util {
private Connection conn;
private Statement stm;
private ResultSet rs;
private String classname="com.mysql.jdbc.Driver";
private String url="jdbc:mysql://localhost:3306/test";
public Util(){
try {
Class.forName(classname);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*获取连接*/
public Connection getConn() {
try {
conn=DriverManager.getConnection(url,"root","123456");
} catch (SQLException e) {
e.printStackTrace(System.err);
conn=null;
}
return conn;
}
/*关闭连接*/
public void closed(){
try {
if (rs!=null) {
rs.close();
}
if (stm!=null) {
stm.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void setConn(Connection conn) {
this.conn = conn;
}
/*执行语句*/
public Statement getStm() {
try {
conn=getConn();
stm=conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stm;
}
public Statement getStmed(){
try {
conn=getConn();
stm=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
} catch (SQLException e) {
e.printStackTrace();
}
return stm;
}
public ResultSet getAllRs(){
String sql="select * from u";
try {
stm=getStmed();
rs=stm.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
// public static void main(String[] args) {
// Util u = new Util();
// ResultSet rr=u.getAllRs();
// try {
// while (rr.next()) {
// System.out.println(rr.getString(1)+"\t"+rr.getString(2)+"\t"+rr.getString(3));
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
}
index.jsp
<body>
<form action="result.jsp" method="post">
<table>
<tr align="center" valign="middle" bgcolor="#CCCCCC" height="22">
<td>id</td>
<td>name</td>
<td>pwd</td>
</tr>
<%
ResultSet rs = (ResultSet)session.getAttribute("resultset");
rs.toString();
while(rs.next()){
%>
<tr align="center" valign="middle" height="22">
<td><%=rs.getString("id") %></td>
<td><%=rs.getString("name") %></td>
<td><%=rs.getString("pwd") %></td>
</tr>
<%} %>
<tr>
<td align="center" colspan="4">
<input type="submit" value="查询全部数据"/>
</td>
</tr>
</table>
</form>
<table>
<tr bgcolor="skyblue">
<td align="center">生成的版权信息</td>
</tr>
<tr>
<td>
<jsp:useBean id="copyright" class="com.count.Copyright"></jsp:useBean>
<jsp:getProperty property="copyrightStr" name="copyright"/>
</td>
</tr>
</table>
</body>
result.jsp
<body>
<jsp:useBean id="db" class="com.count.Util" scope="page"></jsp:useBean>
<%
ResultSet rs = db.getAllRs();
session.setAttribute("resultset", rs);
response.sendRedirect("index.jsp");
%>
</body>
1.PNG
2.PNG