使用JDBC的连接方式查询数据:
import java.sql.*; public class JDBCDemo { /*连接参数常量*/ private static final String JDBC_URL = "jdbc:mysql:///mybatis?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8"; private static final String USER = "root"; private static final String PWD = "root"; public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { /*加载驱动*/ Class.forName("com.mysql.jdbc.Driver"); /*获得连接对象*/ connection = DriverManager.getConnection(JDBC_URL, USER, PWD); /*SQL*/ String sql = "select * from user where id = ?"; /*将SQL传入*/ preparedStatement = connection.prepareStatement(sql); /*设置SQL参数*/ preparedStatement.setInt(1, 1); /*执行SQL 返回数据*/ resultSet = preparedStatement.executeQuery(); /*遍历结果集*/ while (resultSet.next()) { System.out.println("id = " + resultSet.getInt("id") + "name = " + resultSet.getString("username")); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { /*关闭所有连接*/ if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
总结JDBC使用的使用有四点不便:
1、使用时频繁的创建、释放连接,造成系统资源的浪费。
2、SQL是硬编码在代码里面,不利于后期的维护以及扩展,耦合性过强。
3、使用占位符的方式设置参数,在后期维护时比较麻烦(修改了SQL的条件,占位符的参数就要修改)。
4、对结果的处理也是硬编码,非常不利于后期的维护。