//方式一 @Test public void test1() throws SQLException { //獲取Driver實現類對象 Driver driver = new Driver(); //jdbc:mysql 協議 //localhost:ip地址 //zoo 數據庫名 String url = "jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC"; //將用戶名和密碼封裝在properties中 Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "root"); Connection conn=driver.connect(url, info); System.out.println(conn); }
//方式2:在如下的程序中,不出先第三方的API,有可移植性 @Test public void test2() throws Exception { //使用反射獲取Driver對象 com.mysql.cj.jdbc.Driver Class clazz = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); //提供連接的數據庫 String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC"; //提供需要的用戶名和密碼 Properties info=new Properties(); info.setProperty("user", "root"); info.setProperty("password", "root"); Connection conn=driver.connect(url, info); System.out.println(conn); }
//方式3:使用DriverManager替換Driver @Test public void test3() throws Exception { //獲取Driver實現類對象 Class clazz = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver =(Driver) clazz.newInstance(); //注冊驅動 DriverManager.registerDriver(driver); String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC"; //獲取連接 Connection connection = DriverManager.getConnection(url, "root", "root"); System.out.println(connection); }
//方式4:可以知識加載驅動,不要顯示注冊驅動了 @Test public void test4() throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC"; Connection connection = DriverManager.getConnection(url, "root", "root"); System.out.println(connection); } @Test public void test5() throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306?serverTimezone=UTC", "root", "root"); System.out.println(connection); }
//方式5:將數據庫連接需要的4個基本信息聲明在配置文件中 @Test public void test6() throws Exception { //讀取配置文件中的基本信息 InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(is); String user = properties.getProperty("user"); String password = properties.getProperty("password"); String url = properties.getProperty("url"); String DrverClass = properties.getProperty("DrverClass"); Class.forName(DrverClass); Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); }
轉載:https://blog.csdn.net/weixin_45371966/article/details/103549042