方式一:Class.forName("com.mysql.jdbc.Driver")
-
该方式最为常用,加载驱动类Driver的时候,Driver内部静态代码块执行,进行驱动注册
try { // 第一步:加载驱动类 Class.forName("com.mysql.jdbc.Driver"); // 第二步:获取连接对象 String url = "jdbc:mysql://localhost:3306/databasename"; Connection conn = DriverManager.getConnection(url, "username", "password"); // 第三步:获取执行SQL语句并拼装SQL语句 String sql = "select * from tablename where username = ? and password = ? "; PreparedStatement pst = conn.prepareStatement(sql); pst.setObject(1, "username"); pst.setObject(2, "password"); // 第四步:获取结果集并处理 ResultSet resultSet = pst.executeQuery(); while (resultSet.next()) { // TODO 处理结果集 } // 第五步:关闭流 if (resultSet != null) { resultSet.close(); } if (pst != null) { pst.close(); } if (conn != null) { conn.close(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
方式二:new com.mysql.jdbc.Driver()
-
该方式会加载两次驱动,浪费资源,且必须依赖jdbc驱动类才可编译通过,如果找不到jar包,则编译都过不去
try { // 第一步:加载驱动类 new com.mysql.jdbc.Driver(); // 第二步:获取连接对象 String url = "jdbc:mysql://localhost:3306/databasename"; Connection conn = DriverManager.getConnection(url, "username", "password"); // 第三步:获取执行SQL语句并拼装SQL语句 String sql = "select * from tablename where username = ? and password = ? "; PreparedStatement pst = conn.prepareStatement(sql); pst.setObject(1, "username"); pst.setObject(2, "password"); // 第四步:获取结果集并处理 ResultSet resultSet = pst.executeQuery(); while (resultSet.next()) { // TODO 处理结果集 } // 第五步:关闭流 if (resultSet != null) { resultSet.close(); } if (pst != null) { pst.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); }
方式三:System.setProperty(“jdbc.driver”,”com.mysql.jdbc.Driver”)
-
该方式为系统属性设置,优点是可以加载多个驱动,不足之处就是设置参数较为复杂,所以也不推荐使用
try { // 第一步:加载驱动类 System.setProperty("jdbc.driver", "com.mysql.jdbc.Driver"); // 第二步:获取连接对象 String url = "jdbc:mysql://localhost:3306/databasename"; Connection conn = DriverManager.getConnection(url, "username", "password"); // 第三步:获取执行SQL语句并拼装SQL语句 String sql = "select * from tablename where username = ? and password = ? "; PreparedStatement pst = conn.prepareStatement(sql); pst.setObject(1, "username"); pst.setObject(2, "password"); // 第四步:获取结果集并处理 ResultSet resultSet = pst.executeQuery(); while (resultSet.next()) { // TODO 处理结果集 } // 第五步:关闭流 if (resultSet != null) { resultSet.close(); } if (pst != null) { pst.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); }