Fetch Data from Database

Learn how to fetch data from database

In order to fetch data from database server select query has to be executed on server. Statement class object is used to execute query on database server.

Statement class has three methods to execute query

  • boolean execute()

    This method used to execute any sql statement. On successful execution it will return true otherwise false.

  • RecordSet executeQuery()

    This method used to execute any sql statement. This method used to fetch data from database ie. Select command.

  • int executeUpdate()

    This method used to execute any sql statement which update databse ie. Update, insert, delete . On execution it will return number of row updated or deleted from databse.

ResultSet Class

Execution of select query on database server returns set of rows as a result. This set of rows sent to client where it is stored in resultSet.
ResultSet object maintains a cursor which points to current row of data. Initially cursor is positioned before first row. This cursor can be moved to next row using next() method of ResultSet class.

Default ResultSet is not updatable and allows cursor to move only in forward direction.


import java.sql.*;  
 public class dataConnect
    public static void main(String arg[]) throws Exception
	  // Load the Driver
	  // Create connection 
	  Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/world","root","root");	  
	  System.out.println("Connected to database");
	  Statement stmt=conn.createStatement();
	  ResultSet rs=stmt.executeQuery("select * from mydata");