0 votes
1.3k views
in JDBC by
How to read data from database in java? Please provide suitable example with code.

1 Answer

0 votes
by

There are following code to read data from database with the help of given code:

package com.developerhelpway.jdbc;

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

public class ReadDataFromDatabase {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String driverName="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/";
        String databaseName="jdbcexamples";
        String userName="root";
        String password="";
        String tableName = "student";
        Connection con = null;
        try{
          Class.forName(driverName);
          con=(Connection) DriverManager.getConnection(url+databaseName, userName, password);
          Statement stat=con.createStatement();
          String sqlQuery = "SELECT * FROM " + tableName;
          ResultSet resultSet = stat.executeQuery(sqlQuery);
          while(resultSet.next()){
              System.out.println("Id: " + resultSet.getInt("id") + " StudentName: " + resultSet.getString("studentName") + " Course: " + resultSet.getString("course") + " Roll:" + resultSet.getInt("roll") );
          }
        }
        catch(Exception e){
          e.printStackTrace();
        }
    }

}
 

Output:

Id: 2 StudentName: Vinod Course: MCA Roll:100

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...