JDBC是Java连接数据库的关键技术,所以必须要使用,但是每一次要使用都要重写8个基本步骤太繁琐,所以这边可以选择封装JDBC进行调用,把一些重复要写的代码放入静态代码块中,随着类的加载而执行,并且只执行一次。
首先在根目录下新建db.properities文件
把链接mysql的基本数据写入db.properities中,因为是连接的mysql数据库所以driver是这种写法,如果是oracle数据库就是不同的写法,所以不同的数据库在写法上大同小异。
url = jdbc:mysql://localhost:3306/test
user = root
password = aqswdefr
driver = com.mysql.jdbc.Driver
新建工具类DBUtils,把JDBC封装起来,方便调用。
public class DBUtills {
private static String url;
private static String user;
private static String password;
private static String driver;
static {
try {
Properties properties = new Properties();
ClassLoader classLoader = DBUtills.class.getClassLoader();
URL res = classLoader.getResource("db.properties");
String path = res.getPath();
properties.load(new FileReader(path));
//获取数据
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
System.out.println(url + " " + password + " " + user);
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Statement stat, Connection conn) {
if( stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if( conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Statement stat, Connection conn, ResultSet rs ) {
if( rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if( stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if( conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
Connection conn = DBUtills.getConn();
if (conn != null) {
System.out.println("连接成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}