Page 266 - IT-802_class_12
P. 266
Statement stmt = dbCon.createStatement();
Then, we invoke the executeQuery() method of the Statement object to execute an SQL query. This method
returns a single ResultSet object. The ResultSet is a table of data returned by a specific SQL statement.
String query =”select * from students”;
ResultSet rs = stmt.executeQuery(query);
Finally, we use the next() method of the ResultSet object to iterate through all the rows of data returned by the
query. When there are no more rows left, the next() method will return false. Since we know there are 5 columns
in the book table, we use a for loop and the getString() method of the ResultSet object to print all the five
columns.
while(rs.next()){
for (int i = 1; i <=5; i++) {
System.out.print(rs.getString(i));
System.out.print(“|”);
}
System.out.println();
}
All the statements described above must be put in a try catch block to catch Exceptions (of the Exception type
SQLException) that can occur while connecting or fetching data from the database.
package javaapplication1;
import java.sql.Connection;
import java.sql.Drivermanager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JavaApplication1 {
public static void main(String[] args) {
String dbURL = “Jdbc:mysql: //localhost:3306/school”;
String username = “root”;
String password = “root@123”;
try{
Connection dbCon = Drivermanager.getConnection(dbURL, username, password);
Statement stmt = dbCon.createStatement();
String query = “select *from students”;
ResultSet rs = stmt.executeQuery(query);
264 Touchpad Information Technology-XII

