连接数据库的五种方法
-
方式一
Driver driver = new Driver(); String url = "jdbc:mysql://localhost:3306/api_com"; Properties properties = new Properties(); properties.setProperty("user","api_com"); properties.setProperty("password","api_com"); Connection connect = driver.connect(url, properties); System.out.println(connect);
- 缺点:静态加载,灵活性差,依赖强
-
方式二
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver)aClass.newInstance(); String url = "jdbc:mysql://localhost:3306/api_com"; Properties properties = new Properties(); properties.setProperty("user","api_com"); properties.setProperty("password","api_com"); Connection connect = driver.connect(url, properties); System.out.println(connect);
-
方式三
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver)aClass.newInstance(); String url = "jdbc:mysql://localhost:3306/api_com"; String user = "api_com"; String password = "api_com"; DriverManager.registerDriver(driver); Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection);
-
方式四
Class.forName("com.mysql.jdbc.Driver");//mysql5.1.6之后可以去掉 String url = "jdbc:mysql://localhost:3306/api_com"; String user = "api_com"; String password = "api_com"; Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection);
使用 Class.forName 自动完成注册驱动,简化代码
-
方式五
Class.forName("com.mysql.jdbc.Driver");//mysql5.1.6之后可以去掉 Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); String url = properties.getProperty("url"); String user = properties.getProperty("user"); String password = properties.getProperty("password"); Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection);
方式五是在方式四的基础上把数据库信息放到配置文件中
这种方式获取连接是使用的最多,推荐使用
连接数据库的五种方法总结如下:
-
方式一:使用
Driver
类的实例直接连接数据库。这是JDBC较早期的一种连接方式,需要显式创建Driver
对象。缺点是静态加载,灵活性差,依赖性强。 -
方式二:通过反射获取
Driver
类,然后创建其实例并连接数据库。此方法不需要事先加载驱动类,但仍然需要手动注册驱动实例。 -
方式三:类似于方式二,但是使用了
DriverManager
来注册驱动,并通过DriverManager
获取连接。这种方式更加符合JDBC的标准做法。 -
方式四:简化了方式三的步骤,利用了JDBC 4.0以后的特性,即驱动会自动被加载和注册,无需手动操作。只需使用
Class.forName()
加载驱动类即可,甚至在某些情况下这一步也不需要。 -
方式五:在方式四的基础上,将数据库连接信息(URL、用户名、密码)从代码中抽离出来,放入外部配置文件中。这样使得配置更加灵活,便于管理和维护,是一种推荐的做法。
随着JDBC规范的发展,方式四和方式五成为了更现代、更简洁、更灵活的数据库连接方式。它们减少了不必要的重复代码,提高了代码的可维护性,并且使得数据库配置的管理更加方便。在实际开发中,通常会选择方式五,因为它结合了自动驱动加载的便利性和外部配置文件的灵活性。