Java jdbc statement executequery

Processing SQL Statements with JDBC

In general, to process any SQL statement with JDBC, you follow these steps:

This page uses the following method, CoffeesTable.viewTable , from the tutorial sample to demonstrate these steps. This method outputs the contents of the table COFFEES . This method will be discussed in more detail later in this tutorial:

public static void viewTable(Connection con) throws SQLException < String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try (Statement stmt = con.createStatement()) < ResultSet rs = stmt.executeQuery(query); while (rs.next()) < String coffeeName = rs.getString("COF_NAME"); int supplierID = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt("SALES"); int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); >> catch (SQLException e) < JDBCTutorialUtilities.printSQLException(e); >>

Establishing Connections

First, establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. This connection is represented by a Connection object. See Establishing a Connection for more information.

Creating Statements

A Statement is an interface that represents a SQL statement. You execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. You need a Connection object to create a Statement object.

For example, CoffeesTable.viewTable creates a Statement object with the following code:

There are three different kinds of statements:

  • Statement : Used to implement simple SQL statements with no parameters.
  • PreparedStatement : (Extends Statement .) Used for precompiling SQL statements that might contain input parameters. See Using Prepared Statements for more information.
  • CallableStatement: (Extends PreparedStatement .) Used to execute stored procedures that may contain both input and output parameters. See Stored Procedures for more information.
Читайте также:  Line Breaks

Executing Queries

To execute a query, call an execute method from Statement such as the following:

  • execute : Returns true if the first object that the query returns is a ResultSet object. Use this method if the query could return one or more ResultSet objects. Retrieve the ResultSet objects returned from the query by repeatedly calling Statement.getResultSet .
  • executeQuery : Returns one ResultSet object.
  • executeUpdate : Returns an integer representing the number of rows affected by the SQL statement. Use this method if you are using INSERT , DELETE , or UPDATE SQL statements.

For example, CoffeesTable.viewTable executed a Statement object with the following code:

ResultSet rs = stmt.executeQuery(query);

Processing ResultSet Objects

You access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor. This cursor is a pointer that points to one row of data in the ResultSet object. Initially, the cursor is positioned before the first row. You call various methods defined in the ResultSet object to move the cursor.

For example, CoffeesTable.viewTable repeatedly calls the method ResultSet.next to move the cursor forward by one row. Every time it calls next , the method outputs the data in the row where the cursor is currently positioned:

ResultSet rs = stmt.executeQuery(query); while (rs.next()) < String coffeeName = rs.getString("COF_NAME"); int supplierID = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt("SALES"); int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); >// .

Closing Connections

When you are finished using a Connection , Statement , or ResultSet object, call its close method to immediately release the resources it’s using.

Alternatively, use a try -with-resources statement to automatically close Connection , Statement , and ResultSet objects, regardless of whether an SQLException has been thrown. (JDBC throws an SQLException when it encounters an error during an interaction with a data source. See Handling SQL Exceptions for more information.) An automatic resource statement consists of a try statement and one or more declared resources. For example, the CoffeesTable.viewTable method automatically closes its Statement object, as follows:

public static void viewTable(Connection con) throws SQLException < String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try (Statement stmt = con.createStatement()) < ResultSet rs = stmt.executeQuery(query); while (rs.next()) < String coffeeName = rs.getString("COF_NAME"); int supplierID = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt("SALES"); int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); >> catch (SQLException e) < JDBCTutorialUtilities.printSQLException(e); >>

The following statement is a try -with-resources statement, which declares one resource, stmt , that will be automatically closed when the try block terminates:

try (Statement stmt = con.createStatement()) < // . >

Источник

Java jdbc statement executequery

Для выборки данных с помощью команды SELECT применяется метод executeQuery :

ResultSet executeQuery("Команда_SQL")

Метод возвращает объект ResultSet, который содержит все полученные данные. Как эти данные получить?

В объекте ResultSet итератор устаналивается на позиции перед первой строкой. И чтобы переместиться к первой строке (и ко всем последующим) необходимо вызвать метод next() . Пока в наборе ResultSet есть доступные строки, метод next будет возвращать true. Типичное перемещение по набору строк:

ResultSet resultSet = statement.executeQuery("SELECT * FROM Products"); while(resultSet.next()) < // получение содержимого строк >

То есть пока в resultSet есть доступные строки, будет выполняться цикл while, который будет переходить к следующей строке в наборе.

После перехода к строке мы можем получить ее содержимое. Для этого у ResultSet определен ряд методов. Некоторые из них:

  • getBoolean() возвращает значение boolean
  • getDate() возвращает значение Date
  • getDouble() возвращает значение double
  • getInt() возвращает значение int
  • getFloat() возвращает значение float
  • getLong() возвращает значение long
  • getNString() возвращает значение String
  • getString() возвращает значение String

В зависимости от того, данные какого тип хранятся в том или ином столбце, мы можем использовать тот или иной метод. Каждый из этих методов имеет две версии:

int getInt(int columnIndex) int getInt(String columnLabel)

Первая версия получает данные из столбца с номером columnIndex. Вторая версия получает данные из столбца с названием columnLabel.

Например, в прошлых темах была создана таблица, которая имеет три столбца:

CREATE TABLE products ( Id INT PRIMARY KEY AUTO_INCREMENT, ProductName VARCHAR(20), Price INT )
import java.sql.*; public class Program < public static void main(String[] args) < try< String url = "jdbc:mysql://localhost/store?serverTimezone=Europe/Moscow&useSSL=false"; String username = "root"; String password = "password"; Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance(); try (Connection conn = DriverManager.getConnection(url, username, password))< Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM Products"); while(resultSet.next())< int name = resultSet.getString(2); int price = resultSet.getInt(3); System.out.printf("%d. %s - %d \n", id, name, price); >> > catch(Exception ex) < System.out.println("Connection failed. "); System.out.println(ex); >> >

Первый столбец в таблице — столбец Id представляет тип int, поэтому для его получения используется метод getInt() . Второй столбец — ProductName представляет строку, поэтому для получения его данных применяется метод getString() . То есть между типом данных и методом есть соответствие. И мы не можем, к примеру, получить значение столбца ProductName с помощью метода getInt.

Также отмечу, что индексация столбцов начинается с 1, а не с 0.

Возможный консольный вывод программы:

C:\Java>javac Program.java C:\Java>java -classpath c:\Java\mysql-connector-java-8.0.11.jar;c:\Java Program 1. iPhone X - 71000 2. Galaxy S9 - 40000 C:\Java>

Однако мы можем точно не знать порядок следования данных полученном наборе. В этом случае мы можем вместо номеров столбцов можно передать названия столбцов:

ResultSet resultSet = statement.executeQuery(«SELECT * FROM Products»); while(resultSet.next())

Источник

Оцените статью