Friday, July 6, 2018

2 to 4 batch : 05 - JULY - 2018

// import jdbc api
import java.sql.*; 
import java.util.Scanner;
public class FetchDataFromTable 
{
public static void main(String[] args) 
{
try 
{
// load driver class
Class.forName("com.mysql.jdbc.Driver");

// get object of connection
Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/july5"
,"root","root");

// get object of statement
Statement st = co.createStatement();

// execute select query and get data of table inside the result-set
ResultSet rs = st.executeQuery("select * from car ");

// in this variable we will keep no of records available inside result-set
int records = 0;

// fetch a single record from the result-set
while(rs.next())
{
// fetch all the columns of this record
String na = rs.getString("name");
String ma = rs.getString("maker");
int mo = rs.getInt("model");
String cs = rs.getString("cost");

System.out.println(na+":"+ma+":"+mo+":"+cs);
                       
                        // increment record by one 
records++;
}

System.out.println("Records are "+records);

// close connection
co.close();

} // end of try
catch (Exception e) 
{
System.out.println("error "+e);
}

} // end of main method
} // end of class

6 comments: