Java Program to Search the Contents of a Table in JDBC
In order to deal with JDBC standard 7 steps are supposed to be followed:
- Import the database
- Load and register drivers
- Create a connection
- Create a statement
- Execute the query
- Process the results
- Close the connection
- Import the database-syntax for importing the sql database in java is-
import java.sql.* ;
- Load and register drivers-syntax for registering drivers after the loading of driver class is
- Creating a database irrespective of SQL or NoSQL. Creating a database using sqlyog and creating some tables in it and fill data inside it in order to search for the contents of a table. For example, the database is named as “hotelman” and table names are “cuslogin” and “adminlogin”.
- Create a connection: Open any IDE where the java executable file can be generated following the standard methods. Creating a package further creating the class. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.
- Searching content in a table, let’s suppose my “cuslogin” table has columns namely “id”, “name”, “email”, “password” and we want to search the customer whose id is 1.
- Initialize a string with the SQL query as follows
String sql="select * from cuslogin where id=1";
If we want to search for any id in general, then the SQL query becomes
String sql="select * from cuslogin where id="+Integer.parseInt(textfield.getText());
The textfield is the area(in Jframe form) where the user types the id he wants to search in the “cuslogin” table.
4.1: Initialize the below objects of Connection class, PreparedStatement class, and ResultSet class(needed for JDBC) and connect with the database as follows
Connection con = null; PreparedStatement p = null; ResultSet rs = null; con = connection.connectDB();
4.2: Now, add the SQL query of step 3.1 inside prepareStatement and execute it as follows:
p =con.prepareStatement(sql); rs =p.executeQuery();
4.3: We check if rs.next() is not null, then we display the details of that particular customer present in “cuslogin” table
4.4: Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for searching the details of the customer whose id is 1, from table “cuslogin”.
Note: both the file viz result.java and connection.java should be inside the same package, else the program won’t give desired output!!
Connection class of JDBC by making an object to be invoked in main(App) java program below in 1B
App/Main Class where the program is compiled and run calling the above connection class object
Output: Based on the values stored inside the “cuslogin” table.
Please Login to comment...