/** * 连接jdbc的5种方式 */ public class jdbc02 { // 方式1: @SuppressWarnings({"all"}) @Test public void test1() throws Exception{ // 1.获得驱动 Driver driver = new Driver(); // 2.获得连接 String url = "jdbc:mysql://localhost:3306/hspdb02"; Properties properties = new Properties(); properties.setProperty("user","root"); properties.setProperty("password","zw20010108"); Connection connect = driver.connect(url, properties); System.out.println(connect); connect.close(); } // 方式2: @SuppressWarnings({"all"}) public void test2() throws Exception{ // 1.获得驱动 Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver = (Driver) aClass.newInstance(); // 2.获得连接 String url = "jdbc:mysql://localhost:3306/hspdb02"; Properties properties = new Properties(); properties.setProperty("user","root"); properties.setProperty("password","zw20010108"); Connection connect = driver.connect(url, properties); System.out.println(connect); connect.close(); } // 方式3: @Test public void test3() throws Exception{ Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver = (Driver) aClass.newInstance(); String url = "jdbc:mysql://localhost:3306/hspdb02"; String user = "root"; String password = "zw20010108"; DriverManager.registerDriver(driver); Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); connection.close(); } // 方式4: @SuppressWarnings({"all"}) @Test public void test4() throws Exception{ /* static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can't register driver!"); } } */ Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/hspdb02"; String user = "root"; String password = "zw20010108"; Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); connection.close(); } // 方式5 @Test public void test5() throws Exception{ Properties properties = new Properties(); properties.load(new FileReader("src\\mysql.properties")); Class.forName(properties.getProperty("Driver")); Connection connection = DriverManager.getConnection( properties.getProperty("url"), properties.getProperty("user"), properties.getProperty("pwd")); System.out.println(connection); connection.close(); } }
在方式5中的配置文件如下:
mysql.properties:
Driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/hspdb02 user=root pwd=*****
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/98948.html