Jdbc主要作用是连接数据库,连接数据库之前首先需要jre包,
private static String username = null;
private static String password = null;
private static String driver = null;
private static String url = null;
static{
try {
Properties pro = new Properties();
InputStream in = DbUtil.class.getClassLoader().getResourceAsStream(“jdbc.properties”);
pro.load(in);
//读取配置
username = pro.getProperty(“username”);
password = pro.getProperty(“password”);
driver = pro.getProperty(“driver”);
url = pro.getProperty(“url”);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取数据库链接
public static Connection getConnection() {
Connection con = null;
try {
//加载驱动
Class.forName(driver);
con = DriverManager.getConnection(url, password, username);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//关闭资源
public static void close(Connection con, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}