Jdbc的详细使用过程

时间:2019-09-02 21:23:26   收藏:0   阅读:75

获取数据库连接信息

导入数据库连接Jar包

   1. 装载相应的数据库的JDBC驱动并进行初始化

// 加载数据库驱动
Class.forName(dbDriver);

   2. 建立JDBC和数据库之间的Connection连接

//获取连接
Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);

   3. 创建Statement或者PreparedStatement接口,执行SQL语句

3.1 创建Statement

//创建Statement
Statement statement = conn.createStatement();
String strSQL = "select * from t_student";
//创建ResultSet
ResultSet rs = statement.executeQuery(strSQL);

3.2 创建PreparedStatement

String strSQL = "select * from t_student where stuId=? and stuName like ?";
PreparedStatement pst = conn.prepareStatement(strSQL);
pst.setString(1, "b4c93f98-e104-4a78-86ad-11f6292692c4");
pst.setString(2, "%李%");
ResultSet rs = pst.executeQuery();

   4. 处理和显示结果

while (rs.next()) {
    Student student = new Student();
    student.setStuId(rs.getString("stuId"));
    student.setStuName(rs.getString("stuName"));
    System.out.println(student);
}

   5. 释放资源

/**
     * 关闭连接Connection
     * 
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                LogUtil.getInstance().error(ex.getMessage());
            }
        }
    }

    /**
     * 关闭Statement
     * 
     * @param st
     */
    public static void closeStatement(Statement st) {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException ex) {
                LogUtil.getInstance().error(ex.getMessage());
            }
        }
    }

    /**
     * 关闭PreparedStatement
     * 
     * @param pst
     */
    public static void closePreparedStatement(PreparedStatement pst) {
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException ex) {
                LogUtil.getInstance().error(ex.getMessage());
            }
        }
    }

    /**
     * 关闭存储过程
     * 
     * @param cs
     */
    public static void closeCallableStatement(CallableStatement cs) {
        if (cs != null) {
            try {
                cs.close();
            } catch (SQLException ex) {
                LogUtil.getInstance().error(ex.getMessage());
            }
        }
    }

    /**
     * 关闭ResultSet
     * 
     * @param rs
     */
    public static void closeResultSet(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                LogUtil.getInstance().error(ex.getMessage());
            }
        }
    }

 

原文:https://www.cnblogs.com/fengfuwanliu/p/11442574.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!