数据库连接方式
方式一
直接使用com.mysql.jdbc.Driver(),属于静态加载,灵活性差,依赖性强
推出方式2
public void connect01() throws SQLException {
//创建dirver对象
Driver driver =new Driver();
String url = "jdbc:mysql://localhost:3306/studb";
//用户名与密码放入properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//建立连接
Connection connection = driver.connect(url,properties);
System.out.println(connection);
}
方式二
利用反射加载Driver类,动态加载,更加灵活
public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/studb";
//用户名与密码放入properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//建立连接
Connection connection = driver.connect(url,properties);
System.out.println(connection);
}
方式三
用DriverManager替代Driver进行统一管理,具有更好的扩展性
public void connect03() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//利用反射加载Driver
Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建url和user和password
String url = "jdbc:mysql://localhost:3306/studb";
String user = "root";
String password = "123456";
// 注册Driver驱动
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
方式四
使用Class.forName 自动完成注册驱动,简化代码,是使用最多的
public void connect04() throws ClassNotFoundException, SQLException {
//利用反射加载Driver类
//在加载Driver类时,完成注册
/*源码
1.静态代码块,在类加载时,会执行一次
2.DriverManager.registerDriver(new Driver));
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
}
*/
Class.forName("com.mysql.cj.jdbc.Driver");
//创建url,user,password
String url = "jdbc:mysql://localhost:3306/studb";
String user = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
方式五
实际开发中比较好的,在方式4上改进,使用配置文件,连接数据库更加灵活
public void connect05() throws IOException, ClassNotFoundException, SQLException {
//通过properties对象获取文件信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\Jdbc\\myjdbc\\mysql.properities"));
//获取相关的值
String user = properties.getProperty("user");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
String password = properties.getProperty("password");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}