Calling createStatement() and executeQuery

This section describes how to run a SELECT query statement with createStatement() and executeQuery().

After a connection object is created correctly, you need to create a statement object from the connection object in order to execute a SQL statement on the SQL Server, see the following two method call examples:

Statement sta = con.createStatement();
sta.executeQuery("SELECT ...");

Here is a sample program that executes a SELECT statement to get the current date from the SQL Server:

/* ExecuteQuery.java
 * Copyright (c) HerongYang.com. All Rights Reserved.
 */
import java.sql.*;
public class ExecuteQuery {
  public static void main(String [] args) {
    Connection con = null;
    try {

// Obtaining a connection to SQL Server
      con = DriverManager.getConnection(
          "jdbc:sqlserver://localhost\\SQLEXPRESS;"
        + "user=herong;password=T0pSecret;"
        + "database=AdventureWorks2019");

// Execute a query statement
      Statement sta = con.createStatement();
      sta.executeQuery("SELECT GETDATE()");
      sta.close();

      con.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The program runs correctly. But you will get no output, since the returning data from the query execution was not retrieved and printed to the screen. See the next tutorial to know how to do this.

herong> java -version
java version "17.0.1" 2021-10-19 LTS

herong> java -cp .;mssql-jdbc-9.4.1.jre16.jar ExecuteQuery.java

Table of Contents

 About This Book

 JDBC (Java Database Connectivity) Introduction

 JDK (Java SE) Installation

 Microsoft SQL Server Express Edition

 Microsoft JDBC Driver for SQL Server

Microsoft JDBC Driver - Query Statements and Result Sets

 Commonly Used JDBC Class Methods

Calling createStatement() and executeQuery

 Receiving ResultSet Objects from executeQuery

 Closing ResultSet Objects - res.close()

 Looping through ResultSet with res.next()

 Retrieving Field Values using res.get*() Methods

 Using ResultSetMetaData Objects to List All Fields

 Microsoft JDBC Driver - DatabaseMetaData Object

 Microsoft JDBC Driver - DDL Statements

 Microsoft JDBC Driver - DML Statements

 SQL Server - PreparedStatement

 SQL Server CLOB (Character Large Object) - TEXT

 SQL Server BLOB (Binary Large Object) - BLOB

 Using Connection Pool with JDBC

 JDBC-ODBC Bridge Driver - sun.jdbc.odbc.JdbcOdbcDriver

 JDBC-ODBC Bridge Driver - Flat Text Files

 JDBC-ODBC Bridge Driver - MS Access

 JDBC-ODBC Bridge Driver - MS SQL Server

 Archived Tutorials

 References

 Full Version in PDF/EPUB