import java.io.InputStream;
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 {
public JdbcUtils() {
super();
// TODO Auto-generated constructor stub
}
private static String driverName;
private static String url;
private static String username;
private static String password;
static {
try {
// 读取配置文件
InputStream in = JdbcUtils.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
Properties prop = new Properties();
prop.load(in);
driverName = prop.getProperty("driverName");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
// 注册驱动
Class.forName(driverName);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() {
Connection conn = null;
try {
conn = (Connection) DriverManager.getConnection(url, username,
password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
}
}
jdbc.properties配置文件
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/user
username=root
password=123456