JDBC最原始的代碼做查詢操作
阿新 • • 發佈:2018-05-18
ride mysq ext drive SQ 代碼 select exe tco
首先編寫一個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) { } } } }
JDBC最原始的代碼做查詢操作