Java resultset column count

Java ResultSetMetaData getColumnCount() method with example?

The getColumnCount() method of the ResultSetMetaData (interface) retrieves the number of the columns of the current ResultSet object.

This method returns an integer value representing the number of columns.

To get the ResultSetMetaData object, you need to:

Register the Driver: Select the required database register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class.

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

Get connection: Create a connection object by passing the URL of the database, username and password of a user in the database (in string format) as parameters to the getConnection() method of the DriverManager class.

Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password");

Create a Statement object: Create a Statement object using the createStatement method of the connection interface.

Statement stmt = con.createStatement();

Execute the Query: Execute the SELECT query using the executeQuery() methods of the Statement interface and Retrieve the results into the ResultSet object.

String query = "Select * from MyPlayers"; ResultSet rs = stmt.executeQuery(query);

Get the ResultSetMetsdata object: Retrieve the ResultSetMetsdata object of the current ResultSet by invoking the getMetaData() method.

ResultSetMetaData resultSetMetaData = rs.getMetaData();

Finally, using the getColumnCount() method of the ResultSetMetaData interface get the number of columns in the table as:

int columnCount = resultSetMetaData.getColumnCount();

Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below:

CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) );

Now, we will insert 7 records in MyPlayers table using INSERT statements —

insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');

Following JDBC program establishes connection with MySQL database, retrieves and displays the number of columns in the MyPlayers table using the getColumnCount() method.

Example

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class ResultSetMetaData_getColumnCount < public static void main(String args[]) throws SQLException < //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established. "); //Creating the Statement Statement stmt = con.createStatement(); //Query to retrieve records String query = "Select * from MyPlayers"; //Executing the query ResultSet rs = stmt.executeQuery(query); //retrieving the ResultSetMetaData object ResultSetMetaData resultSetMetaData = rs.getMetaData(); //Retrieving the column count of the current table int columnCount = resultSetMetaData.getColumnCount(); System.out.println("Number of columns in the table represented by the current ResultSet object are: "+ columnCount); >>

Output

Connection established. Number of columns in the table represented by the current ResultSet object are: 6

Источник

How to get column count in a ResultSet in JDBC?

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.

//Retrieving the ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData(); //getting the column type int column_count = rsmd.getColumnCount();

Let us create a table with name employee_data in MySQL database using CREATE statement as shown below −

CREATE TABLE employee_data( id INT, Name VARCHAR(255), DOB date, Location VARCHAR(40) );

Following JDBC program establishes connection with the database, retrieves the ResultSetMetaData object of the employee_data table, and prints the number of columns in it.

Example

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; public class NumberOfColumns < public static void main(String args[])throws Exception < //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established. "); //Creating a Statement object Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from employee_data"); //Retrieving the ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData(); //getting the column type int column_count = rsmd.getColumnCount(); System.out.println("Number of columns in the table : "+column_count); >>

Output

Connection established. Number of columns in the table : 4

Источник

How to get Row and Column Count from ResultSet in JDBC

The last() method of the ResultSet interface moves the cursor to the last row of the ResultSet and, the getRow() method returns the index/position of the current row.

Therefore, to get the number of rows move the cursor to the last row using the last() method and get the position of that (last) row using the getRow() method.

Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −

CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) );

Now, we will insert 7 records in MyPlayers table using INSERT statements −

insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');

Following JDBC program establishes a connection with the database and retrieves the contents of the MyPlayers table into a ResultSet object and retrieves the number of rows in the table and displays it.

Example

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RS_Row_Count < public static void main(String args[]) throws Exception < //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established. "); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("select * from MyPlayers"); //Moving the cursor to the last row rs.last(); System.out.println("Table contains "+rs.getRow()+" rows"); >>

Output

Connection established. Table contains 7 rows

Column count

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.

//Retrieving the ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData(); //getting the column type int column_count = rsmd.getColumnCount();

Following JDBC program establishes connection with the database, retrieves the ResultSetMetaData object of the MyPlayers table, and prints the number of columns in it.

Example

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.sql.ResultSetMetaData; public class RS_ColumnCount < public static void main(String args[]) throws Exception < //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established. "); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("select * from MyPlayers"); ResultSetMetaData rsMetaData = rs.getMetaData(); //Moving the cursor to the last row System.out.println("Table contains "+rsMetaData.getColumnCount()+" columns"); >>

Output

Connection established. Table contains 6 columns

Источник

Примеры получения количества столбцов и строк ResultSet в JDBC

Вы можете получить количество столбцов в таблице, используя метод getColumnCount() интерфейса ResultSetMetaData. При вызове этот метод возвращает целое число, представляющее количество столбцов в текущем объекте ResultSet.

//Retrieving the ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData(); //getting the column type int column_count = rsmd.getColumnCount();

Давайте создадим таблицу с именем employee_data в базе данных MySQL, используя инструкцию CREATE.

CREATE TABLE employee_data( id INT, Name VARCHAR(255), DOB date, Location VARCHAR(40) );

После этого программа JDBC устанавливает соединение с базой данных, получает объект ResultSetMetaData таблицы employee_data и печатает количество столбцов в ней.

Пример получения количества столбцов

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; public class NumberOfColumns < public static void main(String args[])throws Exception < //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established. "); //Creating a Statement object Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from employee_data"); //Retrieving the ResultSetMetaData object ResultSetMetaData rsmd = rs.getMetaData(); //getting the column type int column_count = rsmd.getColumnCount(); System.out.println("Number of columns in the table : "+column_count); >>

Вывод

Connection established. Number of columns in the table : 4

Всякий раз, когда мы выполняем операторы SQL с помощью метода executeQuery(), он возвращает объект ResultSet, который содержит табличные данные, возвращаемые запросами SELECT (в целом).

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

Интерфейс ResultSet предоставляет различные методы для поиска, столбцы no.of, имя столбца, тип столбца и т. Д., Но он не предоставляет никакого метода для непосредственного нахождения количества строк.

Используя функцию count (*) в запросе SELECT, вы можете получить количество строк в таблице как:

select count(*) from Table_Name;

Давайте создадим таблицу с именем MyPlayers в базе данных MySQL с помощью оператора CREATE:

CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) );

Теперь мы вставим 7 записей в таблицу MyPlayers, используя операторы INSERT –

insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');

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

Пример нахождения количества строк

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RS_Row_Count < public static void main(String args[]) throws Exception < //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established. "); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("select count(*) from MyPlayers"); rs.next(); //Moving the cursor to the last row System.out.println("Table contains "+rs.getInt("count(*)")+" rows"); >>

Вывод

Connection established. Table contains 8 rows

Получение количества строк с использованием методов

Метод last() интерфейса ResultSet перемещает курсор в последнюю строку ResultSet, а метод getRow() возвращает индекс / позицию текущей строки.

Поэтому, чтобы получить количество, переместите курсор на последнюю строку с помощью метода last() и получите положение этой (последней) строки с помощью метода getRow().

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RS_Row_Count < public static void main(String args[]) throws Exception < //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established. "); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("select * from MyPlayers"); //Moving the cursor to the last row rs.last(); System.out.println("Table contains "+rs.getRow()+" rows"); >>
Connection established. Table contains 8 rows

Средняя оценка 4 / 5. Количество голосов: 1

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

Читайте также:  Jquery bind on html change
Оцените статью