How to Use Different Row Methods to Get Number of Rows in a Table in JDBC?
Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. For different databases, different jar files are imported to make a connection given below or their built path is supposed to be added for specific databases.
- Types of Database
Illustration: SQL and Oracle databases are mostly used for illustration. Here SQL database is taken into consideration. Here Table_Name is Table name. Here it will take all columns and count the rows.
Input: Existing data in the table is shown in the below image
- SQL server used: sqljdbc4.jar
- SQL table used
CREATE TABLE `studentsdetails` ( `id` int(6) unsigned NOT NULL, `Name` varchar(50) NOT NULL, `caste` varchar(10) NOT NULL, `NeetMarks` int(11) NOT NULL, `gender` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
A less efficient way of creating a query
select count(*) from Table_Name;
A more efficient way of creating a query
select count(1) from Table_Name;
This query will take the first column and count the rows. As mostly, Primary key is the first column, it is ideal enough as the Primary key is always unique and not null.
Example 1 Example 2 It will give only one row as output containing a number of rows. Hence, ‘resultset’ will be kept as next itself. select * will bring the whole resultset and the cursor is forced to move last and finally ‘resultset.getRow()’ method will give the number of rows. It is more efficient It is comparatively less efficient
Example 1: To get the number of rows in a table in JDBC by selecting count(1) from ‘studentsdetails’ will provide the result as 5.
Example 2: To get the number of rows in a table in JDBC
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.