Executing SELECT query using Java

In my previous articles about Java JDBC, I showed How to connect Java applications to MySQL. In this article, I will show you how to execute a SELECT query from your Java application.

Executing SELECT query using Java

n my previous articles about Java JDBC, I showed How to connect Java applications to MySQL. In this article, I will show you how to execute a SELECT query from your Java application.

Requirements

  • A MySQL table with one or more records – If you don’t know how to create a table and insert records into it, read this article first.

Here’s how my table looks like.

1JohnAustralia
2LeeChina

Importing packages

Before starting, import the following package.

import java.sql.*;

Creating database connection

To execute our SQL query from Java, we must create a connection first. The getConnection() method takes connection url as the first parameter and username and password as the second and third parameters.

String connUrl="jdbc:mysql://localhost/javadb?;
Connection conn=DriverManager.getConnection(connUrl,"database_username","password");
/*Replace database_name with your database name and password with your database password.*/

Creating a SELECT query

First, let’s create a simple SELECT query.

SELECT * FROM USERS;

This will return all records from the table. Now let’s put this to our Java code.

Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("SELECT * FROM users");
//Replace users with your database name

Displaying the result

Here, we are going to display the name and age from the result.

while(rs.next()) 
{ 
    name=rs.getString("_name");
    age=rs.getString("country")
    System.out.println("Name :" + name + "and Country :" + country);
}
conn.close(); //closing the connection

Full source code of the program is:

import java.sql.*;
public class JavaDemoApp {
    public static void main(String[] args) 
    {
        try
        {
            String name="";
            Class.forName("com.mysql.cj.jdbc.Driver");
            String connUrl="jdbc:mysql://localhost/javadb?";
    Connection conn=DriverManager.getConnection(connUrl,"root","");
    String sql="select * from users";
    Statement st=conn.createStatement();
    ResultSet rs = st.executeQuery(sql);
            while(rs.next()) 
            { 
                name=rs.getString("_name");
                JOptionPane.showMessageDialog(rootPane, name);
            }
            conn.close();
        }
        catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }
}

Share Tweet Send
Loading...