Java resultset как прочитать массив boolean
Перейти к содержимому

Java resultset как прочитать массив boolean

  • автор:

Java – Getting Boolean from ResultSet

ResultSet#getBoolean seems to return false when it's null.
Is there an easy way to get a Boolean (not boolean ) from a ResultSet ?

Best Solution
Related Solutions
Java – Create ArrayList from array
Java – How to call one constructor from another in Java

Yes, it is possible:

To chain to a particular superclass constructor instead of one in the same class, use super instead of this . Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

Java ResultSet Tutorial

Java ResultSet Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java ResultSet interface is a part of the java.sql package. It is one of the core components of the JDBC Framework. ResultSet Object is used to access query results retrieved from the relational databases.

ResultSet maintains cursor/pointer which points to a single row of the query results. Using navigational and getter methods provided by ResultSet, we can iterate and access database records one by one. ResultSet can also be used to update data.

Java ResultSet Hierarchy

Java ResultSet Class HierarchyJava ResultSet Class Hierarchy

The above diagram shows the place of ResultSet in the JDBC Framework. ResultSet can be obtained by executing SQL Query using Statement, PreparedStatement or CallableStatement.

AutoCloseable, Wrapper are super interfaces of ResultSet. Now we will see how to work with ResultSet in our Java programs.

ResultSet Example

We will be using MySQL for our example purpose. Use below DB script to create a database and table along with some records.

Let’s have look at the below example program to fetch the records from the table and print them on the console. Please make sure you have the MySQL JDBC driver in the project classpath.

Output:

Explanation:

  • ResultSet is obtained by calling the executeQuery method on Statement instance. Initially, the cursor of ResultSet points to the position before the first row.
  • The method next of ResultSet moves the cursor to the next row. It returns true if there is further row otherwise it returns false.
  • We can obtain data from ResultSet using getter methods provided by it. e.g. getInt(), getString(), getDate()
  • All the getter methods have two variants. 1st variant takes column index as Parameter and 2nd variant accepts column name as Parameter.
  • Finally, we need to call close method on ResultSet instance so that all resources are cleaned up properly.

ResultSet Types & Concurrency

We can specify type and concurrency of ResultSet while creating an instance of Statement, PreparedStatement or CallableStatement.

statement.createStatement(int resultSetType, int resultSetConcurrency)

ResultSet Types

1) Forward Only (ResultSet.TYPE_FORWARD_ONLY)

This type of ResultSet instance can move only in the forward direction from the first row to the last row. ResultSet can be moved forward one row by calling the next() method. We can obtain this type of ResultSet while creating Instance of Statement, PreparedStatement or CallableStatement.

2) Scroll Insensitive (ResultSet.TYPE_SCROLL_INSENSITIVE)

Scroll Insensitive ResultSet can scroll in both forward and backward directions. It can also be scrolled to an absolute position by calling the absolute() method. But it is not sensitive to data changes. It will only have data when the query was executed and ResultSet was obtained. It will not reflect the changes made to data after it was obtained.

3) Scroll Sensitive (ResultSet.TYPE_SCROLL_SENSITIVE)

Scroll Sensitive ResultSet can scroll in both forward and backward directions. It can also be scrolled to an absolute position by calling the absolute() method. But it is sensitive to data changes. It will reflect the changes made to data while it is open.

ResultSet Concurrency

1) Read Only (ResultSet.CONCUR_READ_ONLY)

It is the default concurrency model. We can only perform Read-Only operations on ResultSet Instance. No update Operations are allowed.

2) Updatable (ResultSet.CONCUR_UPDATABLE)

In this case, we can perform update operations on ResultSet instance.

ResultSet Methods

We can divide ResultSet methods into the following categories.

  • Navigational Methods
  • Getter/Reader Methods
  • Setter/Updater Methods
  • Miscellaneous Methods — close() and getMetaData()

1. ResultSet Navigational Methods

  • boolean absolute(int row) throws SQLException**:** This method moves ResultSet cursor to the specified row and returns true if the operation is successful.
  • void afterLast() throws SQLException**:** This method moves ResultSet cursor to the position after the last row.
  • void beforeFirst() throws SQLException**:** This method moves ResultSet cursor to the position before the first row.
  • boolean first() throws SQLException: This method moves ResultSet cursor to the first row.
  • boolean last() throws SQLException: This method moves ResultSet cursor to the last row.
  • boolean next() throws SQLException: This method moves ResultSet cursor to the next row.
  • boolean previous() throws SQLException: This method moves ResultSet cursor to the previous row.

Output:

2. ResultSet Getter/Reader Methods

  • int getInt(int columnIndex) throws SQLException: This method returns value of specified columnIndex as int.
  • long getLong(int columnIndex) throws SQLException: This method returns value of specified columnIndex as long
  • String getString(int columnIndex) throws SQLException: This method returns value of specified columnIndex as String
  • java.sql.Date getDate(int columnIndex) throws SQLException: This method returns value of specified columnIndex as java.sql.Date
  • int getInt(String columnLabel) throws SQLException: This method returns value of specified column name as int.
  • long getLong(String columnLabel) throws SQLException: This method returns value of specified column name as long.
  • String getString(String columnLabel) throws SQLException: This method returns the value of the specified column name as String.
  • java.sql.Date getDate(String columnLabel) throws SQLException: This method returns the value of the specified column name as java.sql.Date.
  • ResultSet contains getter methods that return other primitive datatypes like boolean, float and double. It also has methods to obtain array and binary data from the database.

3. ResultSet Setter/Updater Methods

  • void updateInt(int columnIndex, int x) throws SQLException: This method updates the value of specified column of current row with int value.
  • void updateLong(int columnIndex, long x) throws SQLException: This method updates the value of the specified column of the current row with long value.
  • void updateString(int columnIndex, String x) throws SQLException: This method updates the value of the specified column of the current row with a String value.
  • void updateDate(int columnIndex, java.sql.Date x) throws SQLException: This method updates the value of specified column of current row with java.sql.Date value.
  • void updateInt(String columnLabel, int x) throws SQLException: This method updates the value of the specified column label of the current row with int value.
  • void updateLong(String columnLabel, long x) throws SQLException: This method updates the value of the specified column label of the current row with long value.
  • void updateString(String columnLabel, String x) throws SQLException: This method updates the value of the specified column label of the current row with a String value.
  • void updateDate(String columnLabel, java.sql.Date x) throws SQLException: This method updates the value of specified columnLabel of current row with java.sql.Date value.

Note: Setter/Updater Methods doesn’t directly update database values. Database values will be inserted/updated after calling the insertRow or updateRow method.

Output:

4. ResultSet Miscellaneous Methods

  • void close() throws SQLException**:** This method frees up resources associated with ResultSet Instance. It must be called otherwise it will result in resource leakage.
  • ResultSetMetaData getMetaData() throws SQLException: This method returns ResultSetMetaData instance. It gives information about the type and property of columns of the query output.

Reference: Java doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Получаем данные из ResultSet

Первую программу мы написали и она отлично отработала. Мы написали запрос, выполнили его, и в результате метод executeQuery() вернул нам объект ResultSet , который содержит все результаты запроса. И теперь мы попробуем разобраться, как эти результаты из него получить.

Результат запроса может содержать тысячи строк и сотни колонок различных типов, так что эта не такая тривиальная задача, как тебе кажется. Например, в базе могут храниться картинки, тогда ты можешь получить картинку в виде набора байт или же InputStream для ее загрузки.

Но начнем мы с самого простого — с понятия “текущей строки результата”. Так как строк у результата обычно очень много, то объект ResultSet имеет у себя внутри указатель на текущую строку. И последовательно переключает строки для их чтения с помощью метода next() .

Такой подход в первую очередь сделан для оптимизации. JDBC Driver может не загружать строки из базы, пока ты последовательно не дойдешь до их чтения. FileInputStream ты тоже читаешь последовательно с начала и до конца. Так что такой подход должен быть тебе знаком и понятен.

Однако же, если тебе очень нужно, то файлы можно читать в любом месте с помощью класса RandomAccessFile .

Класс ResultSet тоже позволяет что-то подобное и позволяет двигать текущую строку по результату куда угодно. Для этого у него есть такие методы:

Метод Описание
1 next() Переключиться на следующую строку
2 previous() Переключиться на предыдущую строку
3 isFirst() Текущая строка первая?
4 isBeforeFirst() Мы перед первой строкой?
5 isLast() Текущая строка последняя?
6 isAfterLast() Мы после последней сроки?
7 absolute(int n) Делает N-ю строку текущей
8 relative(int n) Двигает текущую строку на N позиций вперед. N может быть getRow() Возвращает номер строки

Методы достаточно простые, однако нужно сделать два пояснения. Результаты как бы обрамлены пустыми строками с обоих сторон. Поэтому изначально текущая строка находится перед первой строкой результата. И чтобы получить первую строку, нужно хотя бы раз вызвать метод next() .

Если ты на последней стоке вызвал метод next() , то ты перешел на строку после последней. Данных из нее прочитать ты не можешь, но никакой ошибки не произойдет. Тут метод isAfterLast() будет возвещать true в качестве результата.

Получение данных из текущей строки

Ты научился виртуозно управлять текущей строкой. Теперь давай разберем, как из нее получать данные. Для этого у объекта ResultSet есть специальные методы, которые все можно описать одним шаблоном:

Впрочем, если у колонки есть имя, то можно получать и по имени колонки:

Ниже я приведу таблицу, которая тебе поможет связать типы данных SQL и методы ResultSet:

SQL Datatype getXXX() Methods
CHAR getString()
VARCHAR getString()
INT getInt()
FLOAT getDouble()
CLOB getClob()
BLOB getBlob()
DATE getDate()
TIME getTime()
TIMESTAMP getTimestamp()

Суть, думаю, ты понял.

Получение разных данных о ResultSet

Как читать данные из текущей строки мы разобрались: и по номеру колонки, и по ее имени. Кстати, а как узнать имя колонки по ее номеру? Или количество колонок в результате?

С одной стороны, если ты пишешь запрос, то ты вроде бы должен все это знать. С другой стороны, мы можем писать программу, которая отображает результат запроса на экран: запрос нам передают и мы хотим просто отобразить на экране (в консоли, веб-странице) все, что нам вернул SQL-сервер.

Для этого у JDBC есть специальный объект – интерфейс ResultSetMetaData . Получить объект этого типа достаточно просто:

У интерфейса ResultSetMetaData есть очень интересные методы. Ниже приведу самые популярные из них:

1 getColumnCount() Возвращает количество колонок результата
2 getColumnName(int column) Возвращает имя колонки
3 getColumnLabel(int column) Возвращает description колонки
4 getColumnType() Возвращает тип колонки: число (специальный код)
5 getColumnTypeName() Возвращает тип колонки: строка
6 getColumnClassName() Возвращает имя java-класса для типа колонки
7 getTableName() Возвращает имя таблицы
8 getCatalogName() Возвращает имя каталога колонки
9 getSchemaName() Возвращает имя схемы базы данных
10 isAutoIncrement(int column) Колонка поддерживает AUTO INCREMENT?
11 isNullable() Колонка может содержать NULL?

Давай с его помощью немного узнаем о нашей таблице:

Важно! Обрати внимание, что колонки нумеруются с 1. Строки, кстати, тоже. Как это необычно, да?

Mapping a boolean with hibernate

There is a concept called a soft delete. While working with different persistence framework, sometimes you may not want to completely delete an entity from the database. I was working with hibernate and I had an entity named “User”. I didn’t want to completely delete this ‘User’ entity, rather than I wanted to keep a simple Boolean flag “deleted”.

At the very beginning I was too frustrated handing Boolean flag with hibernate. I was getting type cast exception. I searched a lot, but didn’t find much information out there. So I was suggested to use text ‘true’ or ‘false’ a flag. But where I can store a single bit, it’s a defiantly bad idea to store a text(varchar). At last I have solved it. I think, this text would be worthy if you face the same problem.

Let me show you how I solved it. here is my entity class ..

So here is my ‘deleted’ flag. Whenever I need to delete my user, I need to change the flag. But normally sql database has no Boolean type. So here we have to maintain a bit or something else, may be tiny integers. So here we need some conversions. If we use bit in sql database, and Boolean in our entity, we’ll need two conversions, bit to Boolean and Boolean to bit.

Doing this type of conversions all the time by hand maybe bad idea and I really didn’t want to do.

So I have to find out a better way.

Here’s the thing. Hibernate supports user type. We can create our own user type. So I have written my own user type. Here it is.

Now life is simple, we just need to add an annotation in our entity.

This time, deleted field will look like-

Now everything is simple, nothing to worry about conversion, you’ll never get type cast exception.

And whenever you need to delete your object, just get the object from database using hibernate, you may use dao layer. Then just change flag, deleted true, and the update it.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *