连接数据库的五种方法
连接数据库的五种方法
方法一
public void method1() throws SQLException { Driver driver = new com.mysql.jdbc.Driver(); String url = "jdbc:mysql://localhost:3306/数据库名"; Properties properties = new Properties(); properties.setProperty("user", "用户名"); properties.setProperty("password", "用户密码"); Connection conn = driver.connect(url, properties); }
方法二
相较于方式一,这里使用反射实例化Driver。
public void method2() throws Exception { Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance(); //Class.forName("com.mysql.jdbc.Driver").getDeclaredConstructor().newInstance(); String url = "jdbc:mysql://localhost:3306/数据库名"; Properties properties = new Properties(); properties.setProperty("user", "用户名"); properties.setProperty("password", "用户密码"); Connection conn = driver.connect(url, properties); }
方法三
用了DriverManager实现数据库的连接。
public void method3() throws Exception { Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance() String url = "jdbc:mysql://localhost:3306/数据库名"; String user = "用户名"; String password = "用户密码"; DriverManager.registerDriver(driver); Connection conn = DriverManager.getConnection(url, user, password); }
方法四
方法三的简略版,不必显式的注册驱动了。因为在DriverManager的源码中已经存在静态代码块,实现了驱动的注册。
/* * 在mysql的Driver实现类中,声明了如下的操作: * static { try { java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Cant register driver!"); } } */ public void testConnection4() throws Exception { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/数据库名"; String user = "用户名"; String password = "用户密码"; Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, user, password); }
方法五
我个人觉得第五种最好,因为他实现了代码和数据的分离,如果需要修改配置信息,直接在配置文件中修改,不需要深入代码 ,如果修改了配置信息,省去重新编译的过程。
public void getConnection5() throws Exception { //1.读取配置文件中的4个基本信息 InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbcTes.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); // Class clazz = Class.forName(driverClass); // Driver driver = (Driver) clazz.newInstance(); // DriverManager.registerDriver(driver); //3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); }
jdbcTest.properties
user=用户名 password=用户密码 url=jdbc:mysql://localhost:3306/数据库名?rewriteBatchedStatements=true driverClass=com.mysql.jdbc.Driver#除了MYSQL也可以是其他数据库得驱动
下一篇:
MySQL数据库——DML语句之增删改