JDBC连接数据库跟释放连接
package com.ssh.action;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/** * 数据库工具类 * @author Administrator * */public class DBUtil {/** * 取得数据库连接 * @return */public static Connection getConnection() {Connection conn = null;try {//取得jdbc配置信息JdbcInfo jdbcInfo =null; ///ConfigReader.getInstance().getJdbcInfo();Class.forName(jdbcInfo.getDriverName());conn = DriverManager.getConnection(jdbcInfo.getUrl(), jdbcInfo.getUsername(), jdbcInfo.getPassword());} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return conn;}/** * 关闭 PreparedStatement(预处理执行语句) 目的:可以防止SQL注入、在特定的驱动数据库下相对效率要高(不绝对)、不需要频繁编译.因为已经预加载了 * @param pstmt */public static void close(PreparedStatement pstmt) {if (pstmt != null) {try {pstmt.close();} catch (SQLException e) {e.printStackTrace();}}}/** * 关闭连接 * @param conn */public static void close(Connection conn) {if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}/** * 关闭数据库结果集的数据表 * @param rs */public static void close(ResultSet rs) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}}/** * 提交事务 * @param conn */public static void commit(Connection conn) {if (conn != null) {try {conn.commit();} catch (SQLException e) {e.printStackTrace();}}}/** * 回滚事务 * @param conn */public static void rollback(Connection conn) {if (conn != null) {try {conn.rollback();} catch (SQLException e) {e.printStackTrace();}}}/** * 自动提交事务 * @param conn * @param autoCommit */public static void setAutoCommit(Connection conn, boolean autoCommit) {if (conn != null) {try {conn.setAutoCommit(autoCommit);} catch (SQLException e) {e.printStackTrace();}}}/** * 关闭执行语句 * @param stmt */public static void close(Statement stmt) {if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}}}
?
?
这只是创建了一个JDBC的工具类:下面我们就如何使用进行书写:
?
public static void main(String[] args) throws Exception {Connection conn = null; PreparedStatement pstmt = null;try {conn = DBUtil.getConnection(); //创建连接String sql=""; //写要操作的sqlpstmt = conn.prepareStatement(sql);//预编译sqlpstmt.setString(1, ""); //?参数赋值pstmt.executeUpdate(); //执行sql}catch(Exception e) {throw e; //如果拦截该异常,必须显示抛出,这样才能抛到servlet中,也可以不用拦截}finally {DBUtil.close(pstmt);DBUtil.close(conn);}}转至:http://www.myexception.cn/database/1394685.html