Java 知识 - JDBC


介绍

JDBC 的目标是使 Java 程序员可以连接任何提供了 JDBC 驱动程序的数据库系统,这样就使得程序员无需对特定的数据库系统的特点有过多的了解,从而大大简化和加快了开发过程。

普通查询

@org.junit.Test
public void test() throws Exception {
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
    String sql  = "select * from users";
    Statement statement = con.createStatement();
    ResultSet resultSet = statement.executeQuery(sql);
    while (resultSet.next()) {
        System.out.println(resultSet.getString("id"));
        System.out.println(resultSet.getString("name"));
    }
}

预编译查询

@org.junit.Test
public void test() throws Exception {
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
    String sql  = "select * from users where id = ?";
    PreparedStatement prepareStatement = con.prepareStatement(sql);
    prepareStatement.setString(1, "1");
    ResultSet resultSet = prepareStatement.executeQuery();
    while (resultSet.next()) {
        System.out.println(resultSet.getString("id"));
        System.out.println(resultSet.getString("name"));
    }
}