@Test public void connect01() throws SQLException { Driver driver = new Driver(); String url = "jdbc:mysql://localhost:3306/demo"; Properties properties = new Properties(); properties.setProperty("user", "root"); properties.setProperty("password", "123456"); Connection connect = driver.connect(url, properties); System.out.println(connect); }
使用反射加载Driver类是动态加载,会更加灵活,可以减少依赖。
@Test public void connect02() throws Exception { Driver driver = (Driver)Class.forName("com.mysql.jdbc.Driver").newInstance(); String url = "jdbc:mysql://localhost:3306/demo"; Properties properties = new Properties(); properties.setProperty("user", "root"); properties.setProperty("password", "123456"); Connection connect = driver.connect(url, properties); System.out.println(connect); }
使用DriverManager替代Driver类进行统一管理,这种方式的代码也会更简洁一些。
@Test public void connect03() throws Exception { // 使用DriverManager替代Driver进行统一管理 Driver driver = (Driver)Class.forName("com.mysql.jdbc.Driver").newInstance(); String url = "jdbc:mysql://localhost:3306/demo"; String user = "root"; String password = "123456"; // 注册驱动 DriverManager.registerDriver(driver); Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); }
这种方式最常用。使用Class.forName()自动完成注册读懂,因为在Driver类的静态代码块中注册了Driver。源码如下:
static { try { // 注册驱动 DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can't register driver!"); } }
因此获取连接的代码可以更简洁,代码如下:
@Test public void connect04() throws Exception { // 使用Class.forName自动完成注册驱动,简化代码 // Driver类静态代码块中注册了Driver /* 1. mysql驱动5.1.6可以无需Class.forName("com.mysql.jdbc.Driver"); 2. 从JDK1.5以后调用了JDBC4,不再需要显示调用class.forName()注册驱动而是自动调用驱动jar包下 META-INF\services\java.sql\Driver文本中的类名称去注册 3. 建议写上,更加明确 */ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/demo"; String user = "root"; String password = "123456"; Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); }
注:
对方式4进行改进,添加配置文件,把用户名、密码、驱动包路径、URL都写在配置文件中,增加程序的灵活性。
创建mysql.properties文件,写入如下内容:
user=root password=123456 url=jdbc:mysql://localhost:3306/demo?rewriteBatchedStatements=true dirver=com.mysql.jdbc.Driver
将配置文件读入到Properties对象中,再从Properties对象获取每个值。代码如下:
@Test public void connect05() throws SQLException, IOException, ClassNotFoundException { // 加载配置文件 Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); // 获取值 String user = properties.getProperty("user"); String password = properties.getProperty("password"); String dirver = properties.getProperty("dirver"); String url = properties.getProperty("url"); Class.forName(dirver); Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); }