JDBC工具类

package com.jdbc.utils;

/**
* JDBC的工具类
*/

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {

private static final String driverClassName;
private static final String url;
private static final String username;
private static final String password;

static {
//获取属性文件中的内容 Properties
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src/db.properties"));
} catch
(FileNotFoundException e) { // TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) { // TODO Auto-generated catch
e.printStackTrace();
}


driverClassName=properties.getProperty("driverClassName");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password"); }

/*
* static { driverClassName = "com.mysql.jdbc.Driver"; url =
* "jdbc:mysql:///test"; username = "root"; password = "oracle";
*
* }
*/

/**
* 注册驱动的方法
*/
public static void loadDriver() {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

/**
* 获得连接的方法
*/

}

public static Connection getConnection() {
Connection conn = null;
try {
loadDriver();// 将驱动一并注册;
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;

}

/**
* 释放资源的方法
*/
public static void release(Statement stmt, Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stmt = null;
}
}

public static void release(ResultSet rs, Statement stmt, Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stmt = null;
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs = null;
}
}

}

posted @ 2020-01-21 23:34  静静学  阅读(137)  评论(0)    收藏  举报