本文主要是通过属性文件来连接数据库,db.properties文件内容如下
#mysql DB properties
driver_class=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/ygw_test
username=root
password=654321
package com.chaoyue.jdbc.util;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 该类封装了连接和关闭数据库连接操作
* @author 超越
* @Date 2016年11月30日,下午3:10:10
* @motto 人在一起叫聚会,心在一起叫团队
* @Version 1.0
*/
public class DBUtil {
public static Connection getConnection() {
Properties prop = new Properties();
FileInputStream fis = null;
Connection con = null;
try {
fis = new FileInputStream("db.properties");
prop.load(fis);
// 加载驱动
Class.forName(prop.getProperty("driver"));
// 建立连接
con = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password"));
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
// 关闭ResultSet
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 关闭PreparedStatement
public static void closePreparedStatement(PreparedStatement pstm) {
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 关闭Statement
public static void closeStatement(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 关闭Connection
public static void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}