底層jdbc查詢操作
@Test
public void jdbcTest(){
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs = null;
//加載驅動
try {
Class.forName("com.mysql.jdbc.Driver");
//創建連接
conn=(Connection) DriverManager.getConnection("jdbc:mysql:///springday03","root","root");
//編寫sql語句
String sql="select * from user where username=?";
//預編譯sql
ps=(PreparedStatement) conn.prepareStatement(sql);
//預編譯設置
ps.setString(1, "lucy");
//執行sql
rs=(ResultSet) ps.executeQuery();
//遍歷結果集
while(rs.next()){
String username=rs.getString("username");
String password=rs.getString("password");
//創建實體類對象,把參數存到實體類打印
User user = new User();
user.setUsername(username);
user.setPassword(password);
//重寫toString方法輸出user
System.out.println(user);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//關閉連接
try {
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}