版权声明:本文为博主原创文章,转载请声明出处。 https://blog.csdn.net/qq_34909297/article/details/79954712
一:
package days_01;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/*
*/
public class DBUtil {
static Properties properties;
static {
properties = new Properties();
//去加载配置文件
try {
properties.load(new FileReader("./src/db.properties"));
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException{
String driverClassName = properties.getProperty("driverClassName");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
// 加载驱动类
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
return DriverManager.getConnection(url,username,password);
}
public static void main(String[] args) throws SQLException {
System.out.println("用户名:"+properties.getProperty("username")+"密码:"+properties.getProperty("password"));
System.out.println("用户名:"+properties.getProperty("url")+"密码:"+properties.getProperty("driverClassName"));
DBUtil db = new DBUtil();
Connection conn = db.getConnection();
System.out.println(conn);
}
}
package day_01;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* v1.0
* @author cxf
*
*/
public class JdbcUtils {
private static Properties props = null;
// 只在JdbcUtils类被加载时执行一次!
static {
// 给props进行初始化,即加载dbconfig.properties文件到props对象中
try {
props = new Properties();
InputStream in = JdbcUtils.class.getClassLoader()
.getResourceAsStream("dbconfig.properties");
props.load(in);
} catch(IOException e) {
throw new RuntimeException(e);
}
// 加载驱动类
try {
Class.forName(props.getProperty("driverClassName"));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
// 获取连接!
public static Connection getConnection() throws SQLException {
// 得到Connection
return DriverManager.getConnection(props.getProperty("url"),
props.getProperty("username"),
props.getProperty("password"));
}
}