A simple Java application showing how to query a table in a database i.e performing a select query using JDBC
Steps for querying a Database using JDBC -
1. Download the driver jar from Internet and place it in classpath of your Java application. Here I am using MySql as Database so I have downloaded the jar with name as : "mysql-connector-java-5.1.20-bin.jar"
2. Create a Database (am using MySql as backend) name as "javaee".
3. Create a table in "javaee" database as "user". Run the create query stated below -
CREATE TABLE user ( 'First Name' varchar(30) , 'Last Name' varchar(30) , 'E-Mail' varchar(45) , 'password' varchar(30) NOT NULL, PRIMARY KEY ('password') )
4. Populate the table user with some data (of your own), if not run the three insert queries stated below -
INSERT INTO user () VALUES ( 'Jonty','Magic','jonty@magic.com','123456'); INSERT INTO user () VALUES ( 'JSP','Servlets','jsp@servlets.com','123'); INSERT INTO user () VALUES ( 'java','sun','java@sun.com','12');
5. Create a Java Class. It will perform necessary select query and output it to browser. The code for Java class is shown below -
package com.hubberspot.jdbc; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class SelectJdbcQuery { Connection connection = null; ResultSet resultSet = null; PreparedStatement preparedStatement = null; String query = null; String url = null; String username = null; String password = null; public static void main(String[] args) { SelectJdbcQuery sjq = new SelectJdbcQuery(); sjq.createConnection(); sjq.executeQuery(); } private void createConnection() { url = "jdbc:mysql://localhost:3306/javaee"; username = "root"; password = "root"; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(url, username , password); } catch (Exception e) { e.printStackTrace(); } } private void executeQuery() { query = "select * from User"; try { preparedStatement = connection.prepareStatement(query); resultSet = preparedStatement.executeQuery(); System.out.println("The Select query has following results : "); System.out.println("\n First Name\t Last Name\t Email"); int i = 0; while(resultSet.next()) { System.out.print(" "+resultSet.getString(1) + " \t"); System.out.print(" "+resultSet.getString(2) + " \t"); System.out.println(" "+resultSet.getString(3) + " \t"); i++; } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Output of the program :