pom.xml
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>
public static void Connection1() throws SQLException { Driver drive=new com.mysql.jdbc.Driver(); String url="jdbc:mysql://localhost:3306/test"; Properties info=new Properties(); info.setProperty("user","root"); info.setProperty("password","root"); Connection connect = drive.connect(url, info); System.out.println(connect); }
public static void Connection2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException { // 1.获取Driver实现类对象:使用反射 Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); // 2.提供要连接的数据库 String url = "jdbc:mysql://localhost:3306/test"; // 3.提供连接需要的用户名和密码 Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "root"); // 4.获取连接 Connection conn = driver.connect(url, info); System.out.println(conn); }
// 1.获取Driver实现类的对象 Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); // 2.提供另外三个连接的基本信息: String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "root"; // 注册驱动 DriverManager.registerDriver(driver); // 获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn);
String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "root"; // 2.加载Driver Class.forName("com.mysql.jdbc.Driver"); // 3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn);
user=root password=root url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true driverClass=com.mysql.jdbc.Driver
InputStream is = connDate.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); //2.加载驱动 Class.forName(driverClass); //3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn);