方式一
Driver driver = new com.mysql.jdbc.Driver(); String url = "jdbc:mysql://localhost:3306/test"; Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password","1234"); Connection connection = driver.connect(url,info); System.out.println(connection);
方式二 使用反射
Class cl = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) cl.newInstance(); String url = "jdbc:mysql://localhost:3306/test"; Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password","1234"); Connection connection = driver.connect(url,info); System.out.println(connection);
方式三 使用Drivermanager
//利用反射 Class cl = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) cl.newInstance(); String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password="1234"; DriverManager.registerDriver(driver); Connection connection = DriverManager.getConnection(url,user,password); System.out.println(connection);
方式4 可以省略显示的驱动加载
String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password="1234"; //利用反射 Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection(url,user,password); System.out.println(connection);
方式5 通过配置文件加载配置信息
InputStream is = connectTest.class.getClassLoader().getResourceAsStream("jdbcInfo.properties"); Properties pro = new Properties(); pro.load(is); String user = pro.getProperty("user"); String password = pro.getProperty("password"); String url = pro.getProperty("url"); String driverClass = pro.getProperty("driverClass"); //利用反射 Class.forName(driverClass); Connection connection = DriverManager.getConnection(url,user,password); System.out.println(connection);