Skip to main content

How to retrieve data from table by using JDBC with example

To retrieve data from mysql data table by using jdbc, we need to confirm weather which table data we need to retrieve. To confirm open your mysql and view all database names by using the 'show databases' commands in mysql. Then select which is your database name from showing list of database names, by using the 'use <database name>' command in mysql.

Then we need to see all your existing tables by executing the 'show tables' command. This command gives you the list of existing tables in your selected database. You need to use existing table only you can follow with that. But, here we will see with entirely new which is not existing in mysql database. Now, We will create simple mysql table with minimal columns.

create table emp(eno integer(10), ename varchar(30), sal float);

The above command creates a new table, we will move further to insert records into emp table by executing the insert which we mentioned in the below.

insert into emp values(1,'javatbrains',50000.0);

If you want to insert multiple records into the same table, you need to execute the same query by entering the different value to insert into the emp table. Now, we will check weather the records are inserted into the emp table or not by executing the select query which will mentioned in the below.

select * from emp;

The above query gives you the list of existing records in the emp table. In our emp table we have inserted two records, so output will be like,

+------+---------------+--------+
| eno   | ename          | sal             |
+------+---------------+--------+
| 1       | javatbrains  | 50000       |
| 2       | nallamachu  | 50000       |
+------+---------------+--------+
2 rows in set (0.00 sec)

Now our aim is to get the same output by retrieving data from database by using jdbc program. There are several statements are exists in jdbc with minimal differences for doing any operations on database tables.

In this example, we will use normal Statement interface in jdbc to retrieve data from mysql database. The below is the jdbc program to retrieve records from database table.

package com.javatbrains.jdbc;

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

public class RetriveRecords {

  static Connection con = null;
  static Statement st = null;
  static ResultSet rs = null;

public static void main(String[] args) {
   try {
     // Register Driver
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());

     // Establish Connection
     con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=root");

     // Create a statement
     st = con.createStatement();

     // Execute the Statement
     rs = st.executeQuery("select * from emp");

     // Retrieve from ResultSet and display column data
     while (rs.next()) {
        System.out.println(rs.getInt(1) + " " + rs.getString(2) + " "+ rs.getFloat(3));
     }
   } catch (SQLException e) {
      e.printStackTrace();
   } finally {
       try {
          con.close();
          st.close();
          rs.close();
       } catch (SQLException e) {
          e.printStackTrace();
       }
    }

  }

}

OutPut:
1 javatbrains 50000.0
2 nallamachu 50000.0

In the above JDBC program differently I have written compare to previous programs. In previous programs we are using Class.forName() method for loading the driver. But, here we will see the way of registering the Driver class by using the DriverManager class. When we will register a Driver there no need to load the Driver again. We will follow any of one way.

Even though while while creating the Connection here different approach I am following in this example. In previous example we use to see the syntax of creating the connection is like,

GetConnection("jdbc:mysql://localhost:3306","root","root");

But, in the current example is following the different approach. But, the both use is same only for making connection with database.

getConnection("jdbc:mysql://localhost:3306/test?user=root&password=root")

Then remaining steps will be the same as the common JDBC steps as we are following in all the examples like, create Statement and execute query and fetch records by using ResultSet.

Related Posts:

Comments

Popular posts from this blog

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Prime, Fibonacci and Factorial number with example in java

Prime number, Fibonacci series and Factorial number programs are most commonly asked questions in interview. Read this article to know what is and how to write programs for prime number, fibonacci series and factorial number. Prime Number: prime number is natural number greater than 1 that has no positive divisor other than 1 and itself. A natural number greater than 1 is not a prime number, is called Composite number . For example, 7 is a prime number. Because it can divide with 1 and 7 only. Where as 8 is composite number. Since it has the divisor 2 and 4 in addition to the 1 and 8. The below example represents the finding the passing number is prime number or not. If the passing number is prime number it will print true otherwise it will print false. package com . javatbrains . practice ; public class PrimeNumber { public boolean isPrimeNumber ( int number ) { if ( number <= 1 ) return false ; // There's only one ...

JVM, JRE and JDK in Java

JVM, JRE and JDK are the most basic common concepts to know in java. These are the basic features to understand how Java architecture works? JVM stands for Java Virtual Machine, which doesn't have any physical directories created in java installation. JRE stands for Java Runtime Environment, which creates the directory under Java installation path and also present in JDK. JDK stands for Java Development Kit, which creates the directory in Java installation path and also it has it's own JRE. Since we have already learn that Java is platform independent means if we have implemented any of the java class in one environment, it will be executed in any other environment and provides the same output. But, JVM, JRE and JDK all are platform dependent . So that, for windows, linux, unix, mac, solaris..etc has it's own JVM, JRE and JDK. One will be not compatible with other environments. While installing the Java, we might come to know a bit about JRE and JDK. But, JVM is the other...