Thursday, October 25, 2007

Jdbc Interview Questions Part2


15. How to make a query?
Create a Statement object and calls the Statement.executeQuery method to select data from the database. The results of the query are returned in a ResultSet object.
Statement stmt = con.createStatement();
ResultSet results = stmt.executeQuery("SELECT data FROM aDatabase ");
________________________________________
16. How can you retrieve data from the ResultSet?
Use get methods to retrieve data from returned ResultSet object.
ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
String s = rs.getString("COF_NAME");
The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs
________________________________________
17. How to navigate the ResultSet?
By default the result set cursor points to the row before the first row of the result set. A call to next() retrieves the first result set row. The cursor can also be moved by calling one of the following ResultSet methods:
o beforeFirst(): Default position. Puts cursor before the first row of the result set.
o first(): Puts cursor on the first row of the result set.
o last(): Puts cursor before the last row of the result set.
o afterLast() Puts cursor beyond last row of the result set. Calls to previous moves backwards through the ResultSet.
o absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row.
o relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward.
________________________________________
18. What are the different types of Statements?
0. Statement (use createStatement method)
1. Prepared Statement (Use prepareStatement method)
2. Callable Statement (Use prepareCall)
________________________________________
19. If you want to use the percent sign (%) as the percent sign and not have it interpreted as the SQL wildcard used in SQL LIKE queries, how to do that?
Use escape keyword. For example:
stmt.executeQuery("select tax from sales where tax like '10\%' {escape '\'}");
________________________________________
20. How to escape ' symbol found in the input line?
You may use a method to do so:
static public String escapeLine(String s) {
String retvalue = s;
if (s.indexOf ("'") != -1 ) {
StringBuffer hold = new StringBuffer();
char c;
for(int i=0; i < s.length(); i++ ) {
if ((c=s.charAt(i)) == '\'' ) {
hold.append ("''");
}else {
hold.append(c);
}
}
retvalue = hold.toString();
}
return retvalue;
}
Note that such method can be extended to escape any other characters that the database driver may interprete another way.
________________________________________

0 comments:

Advertisement

 

Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com