JavaBean专题

获取数据库连接

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(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }
    
    
    public void setConn(Connection conn) {
        this.conn = conn;
    }
    public Statement getStm() {
        return stm;
    }
    public void setStm(Statement stm) {
        this.stm = stm;
    }
    public ResultSet getRs() {
        return rs;
    }
    public void setRs(ResultSet rs) {
        this.rs = rs;
    }
    
}

index.jsp

    <form action="result.jsp" method="post">
        <table>
            <tr>
                <td align="center" height="60" valign="middle">
                    <input type="submit" value="获取连接">
                </td>
            </tr>
        </table>
    </form>

result.jsp

    <jsp:useBean id="db" class="com.count.Util"></jsp:useBean>
    <%
        Connection conn=db.getConn();
    %>
    Connection:<jsp:getProperty property="conn" name="db"/>
    <br>
    Statement:<jsp:getProperty property="stm" name="db"/>
    <br>
    ResultSet:<jsp:getProperty property="rs" name="db"/>
捕获.PNG
上一篇下一篇

猜你喜欢

热点阅读