I am trying to write this method in java dao to operate mysql database and I cou
ID: 3830798 • Letter: I
Question
I am trying to write this method in java dao to operate mysql database and I could not get it right. Can someone help me with what's wrong? Here is my code:
public List<Books> searchBooksById(int bookid) throws SQLException{
Connection conn = Conn();
List<Books> list = new ArrayList<>();
String sql = "SELECT * from books where bookid = ?";
PreparedStatement state = conn.prepareStatement(sql);
state.setInt(1, bookid);
try{
ResultSet rs = state.executeQuery(sql);
while(rs.next()){
Books books = new Books();
books.setbookid(rs.getInt("bookid"));
books.settitle(rs.getString("title"));
books.setisbn(rs.getString("isbn"));
books.setPublishdate(rs.getString("publishdate"));
books.setauthorid(rs.getInt("authorid"));
books.setpublisherid(rs.getInt("publisherid"));
list.add(books);
}
}catch(SQLException e){
e.printStackTrace();
}
return list;
}
Explanation / Answer
1) Here in your defined function you are passing bookid as parameter value but i don't see this variable defined in your function, is it a global variable used or just a miss.
2) I don't see gettingConnection using Driver manager.Once we create instance of Connection class then we need to use getConnection method of DriverManager class to open a connection of particular driver type.Something like below
Connection conn = null;
conn = DriverManager.getConnection( "jdbc:mysql:// yourServername: portNumber/userName,password");
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.