Friday, 27 November 2015

java program with MySQL to retrieve database records using select


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Second {

public static void main(String[] args) {
// TODO Auto-generated method stub
String query = "select * from persons";
Connection con = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root", "root");
stmt = con.createStatement();
ResultSet res = stmt.executeQuery(query);
//System.out.println("No.of Inserted Records == > " + i);

while(res.next()){
System.out.println(res.getInt(1));
System.out.println(res.getString(2));
System.out.println(res.getString(3));
System.out.println(res.getString(4));
System.out.println(res.getString(5));
System.out.println("================");

}

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {

try {
stmt.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

Output:-
1
sai
prasad
Kasturi Nagr
bangalore
================
2
Prasad
ram
Ram Nagar
Bangalore
================
3
Prasad
ram
Ram Nagar
Bangalore
================
4
babu
ram
Krishna Nagar
Bangalore
================
5
Chaya
Prasad
Banishankari
Bangalore
================
6
Krishna
Prasad babau
Banishankari stage
Mangalore
================

No comments:

Post a Comment