JDBC最原始的代码做查询操作

首先编写一个User类。

public class User {

    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password + "]";
    }

然后再编写一个单元测试类,编写JDBC最原始的代码做查询操作。

public class JdbcTemplateDemo2 {

    // jdbc最原始的代码做查询操作
    @Test
    public void testJDBC() {
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///spring_lee", "root", "yezi");
            String sql = "select * from user where username=?";
            // 对sql进行预编译操作
            psmt = conn.prepareStatement(sql);
            psmt.setString(1, "mary");
            // 执行sql
            rs = psmt.executeQuery();
            // 遍历结果
            while (rs.next()) {
                String username = rs.getString("username");
                String password = rs.getString("password");

                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                System.out.println(user);
            }
        } catch (Exception e) {

        } finally {
            try {
                rs.close();
                psmt.close();
                conn.close();
            } catch (Exception e2) {

            }
        }
    }       

}

 

posted @ 2018-05-17 23:12  秦先生的客栈  Views(302)  Comments(0Edit  收藏  举报