import com.mysql.jdbc.Driver;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* 分析java连接mysql的5种方式
*/
public class JdbcConn {
//方式1
@Test
public void Connect01() throws SQLException {
Driver driver = new Driver(); //创建driver对象
String url = "jdbc:mysql://localhost:3306/imooc1";
Properties properties = new Properties(); //创建properties对象
properties.setProperty("user", "root"); //将用户名和密码放入properties对象
properties.setProperty("password", "123456");
Connection connection = driver.connect(url, properties); //连接
System.out.println(connection);
}
//方式2
@Test
public void Connect02() throws Exception {
//使用反射加载Driver类,动态加载,更加的灵活,减少依赖性
Class<?> class1 = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) class1.getConstructor().newInstance();
String url = "jdbc:mysql://localhost:3306/imooc1";
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "123456");
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
//方式3 使用 DriverManager 替代 driver 进行统一管理
@Test
public void Connect03() throws Exception {
Class class2 = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)class2.getConstructor().newInstance();
//创建url,user,password
String url = "jdbc:mysql://localhost:3306/imooc1";
String user = "root";
String password = "123456";
DriverManager.registerDriver(driver); //注册Driver驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式4 使用Class.forName自动完成注册驱动,简化代码
//这种方式获取连接是使用的最多的,推荐使用
@Test
public void Connect04() throws Exception {
//在加载 Driver类时,完成注册
/**
* 源码:1.静态代码块在类加载时,会执行一次
* static {
* try {
* DriverManager.registerDriver(new Driver());
* } catch (SQLException var1) {
* throw new RuntimeException("Can't register driver!");
* }
* }
* 2.因此注册driver的工作已经完成
*/
Class.forName("com.mysql.jdbc.Driver"); //此句也可以不写,但建议写上
//创建url,user,password
String url = "jdbc:mysql://localhost:3306/imooc1";
String user = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式5 在方式4的基础上改进,增加配置文件,让连接mysql更加灵活
//在实际开发中最好的一种方式
@Test
public void Connect05() throws Exception {
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src/mysql.properties"));
//读取相关的值
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
JDBC:Java连接MySQL的5种方式
最新推荐文章于 2024-08-14 20:51:38 发布