Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses
Showing posts with label Database Programming in Java. Show all posts
Showing posts with label Database Programming in Java. Show all posts

Dynamic loading of JDBC (Database) Connection Properties in Java

Program to demonstrate how to load JDBC Connection properties in Java dynamically.

1. Create JDBC Database Connection Properties file for MySql (connection.properties)

# Database Properties

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/sample
database.user=root
database.password=root


2. Create a Java class for loading of this properties.
package com.hubberspot.example;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class DatabaseConnection {

 public static void main(String[] args) throws IOException {
 
  File propertiesFile = new File("F:/Java/Spring/workspace/Java/src/connection.properties");
  FileReader fileReader = new FileReader(propertiesFile);
  
  Properties props = new Properties();
  props.load(fileReader);
  
  String driver = props.getProperty("database.driver");
  String url = props.getProperty("database.url");
  String user = props.getProperty("database.user");
  String password = props.getProperty("database.password");
  
  System.out.println("Driver : " + driver);
  System.out.println("Url : " + url);
  System.out.println("User : " + user);
  System.out.println("Password : " + password);

 }
 
}



Output of the program :



In future, if you wish to change the database say from MySql to Oracle, than just you need to change connection.properties file.See below :

1. Create JDBC Database Connection Properties file for Oracle (connection.properties)

# Database Properties

database.driver=oracle.jdbc.driver.OracleDriver
database.url=jdbc:oracle:thin:@localhost:1521:sample
database.user=root
database.password=root


After running the above Java class again we get the output as :

Output of the program : 

 


How to perform delete sql query in JSP and Servlets using JDBC ?



A simple web application showing how to query a table in a database i.e performing a delete query using JDBC

Steps for querying a Database using JDBC -

1. Download the driver jar from Internet and place it in WEB-INF/lib folder of your Web 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 "customer". Run the create query stated below -

CREATE TABLE customer (
   'First Name' varchar(30) ,
   'Last Name' varchar(30) ,
   'E-Mail' varchar(45) ,
   'City' varchar(30) ,
   'password' varchar(30) NOT NULL,
   PRIMARY KEY ('password')
 ) 



4. Populate the table user with some data (of your own), if not run the four insert queries stated below -

insert into customer () values ('Jonty','Magic','jonty@magic.com','Pune','123456');

insert into customer () values ('Java','Sun','java@sun.com','New York','456');

insert into customer () values ('Jesse','lool','jesse@lool.com','Jamaica','23456');

insert into customer () values ('Cameroon','Black','cameroon@black.com','Sydney','34');



5. Create a Servlet. It will perform necessary update query. The code for servlet 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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DeleteJdbcQueryServlet")
public class DeleteJdbcQueryServlet extends HttpServlet {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 static String query = null;
 String url = null;
 String username = null;
 String password = null;

 public void init(ServletConfig config) throws ServletException {

  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();
  }

 }


 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  doPost(request, response);

 }


 protected void doPost(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  query = "delete from customer where First_Name='Jonty';";

  executeQuery(query);

  query = "delete from customer where First_Name='Java';";

  executeQuery(query);
 }

 private void executeQuery(String query) {

  try {

   statement = connection.createStatement();
   statement.execute(query);

  }
  catch (SQLException e) {

   e.printStackTrace();

  }
 } 

 @Override
 public void destroy() {
  try {    
   statement.close();
   connection.close();
  }
  catch (SQLException e) {

   e.printStackTrace();
  } 

 }

}





Output after Insert query -











Output after Delete query -



How to perform create sql query in a Java application using JDBC ?



A simple Java application showing how to query a table in a database i.e performing a create 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 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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CreateJdbcQuery {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 String query = null;
 String url = null;
 String username = null;
 String password = null;

 public static void main(String[] args) {

  CreateJdbcQuery cjq = new CreateJdbcQuery();
  cjq.createConnection();
  cjq.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 = "create table user " +      
    "(First_Name varchar(20) NOT NULL,"+    
    "Last_Name varchar(30) NOT NULL,"+
    "Email varchar(50) NOT NULL,"+
    "City varchar(30) NOT NULL,"+    
    "password varchar(30) NOT NULL PRIMARY KEY "+    
    ");";
  
  try {
   
   statement = connection.createStatement();
   statement.execute(query);
            
  }
  catch (SQLException e) {

   e.printStackTrace();
  }
  finally {
   try {    
    statement.close();
    connection.close();
   }
   catch (SQLException e) {

    e.printStackTrace();
   } 
  }

 }

}




How to perform select sql query in a Java application using JDBC ?



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 :



How to create a Filter that adds url and time of request to a database in JSP and Servlets ?.

A simple Web Application demonstrating the usage of Filters in Java EE. Here it is showing how to create a Filter that adds url and time of request to a database in JSP and Servlets.


package com.hubberspot.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

//Any request accessed by pattern /* will be intercepted by this
//filter whose name is DatabaseEntryFilter. No web.xml is needed 
//if we are using annotations
@WebFilter(urlPatterns={"/*"} , filterName="DatabaseEntryFilter" )
public class DatabaseEntryFilter implements Filter {
 // This filter implements Filter so it has to provide implementations
 // for Filter interface 

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 static String query = null;
 String url = null;
 String username = null;
 String password = null;
 private FilterConfig filterConfig = null;

 public FilterConfig getFilterConfig() {
  return filterConfig;
 }

 public void setFilterConfig(FilterConfig fConfig) {
  this.filterConfig = fConfig;
 }

 // 3rd implementation of Filter interface
 public void destroy() {
  this.filterConfig = null;
 }

 // 2nd implementation of Filter interface 
 public void doFilter(
   ServletRequest servletRequest, 
   ServletResponse servletResponse, 
   FilterChain chain
   ) throws IOException, ServletException {

  // extracting the ServletContext from filterConfig
  ServletContext context = filterConfig.getServletContext();
  // Taking incoming time of request
  double incomingTime = System.currentTimeMillis();

  // Pre processing of filter before doFilter() method
  chain.doFilter(servletRequest, servletResponse); // here request goes to server
  // Post processing of filter before doFilter() method  

  // Taking outgoing time of response
  double outgoingTime = System.currentTimeMillis();

  String diffInTime = "" ;  
  String url = "";
  String client = "";
  String date = "";

  // Downcasting to HttpServletRequest
  HttpServletRequest request = (HttpServletRequest)servletRequest;
  // Extracting the URL of request
  url = request.getRequestURI();
  // Extracting the remote address of request
  client = request.getRemoteAddr();
  // Extracting the time difference 
  diffInTime= (outgoingTime - incomingTime)/1000.0 + "secs";
  // creating a new Date object 
  date = new Date().toString();
  // making the following insert query each time a 
  //new request is made to the server
  query = "insert into status () values " +
    "('"+ client + "','" + url + "','" + date + "','" + diffInTime + "');";
  executeQuery(query);

 }

 private void executeQuery(String query) {
  try {

   statement = connection.createStatement();
   statement.execute(query);

  }
  catch (SQLException e) {

   e.printStackTrace();

  }
 }

 // 3rd implementation of Filter interface
 public void init(FilterConfig fConfig) throws ServletException {
  this.filterConfig = fConfig;
  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();
  }
 }
}




Inserted Queries result in database on browsing few links :











Video tutorial to demonstrate @WebFilter annotation. 





Using annotation





How to perform delete sql query in a Java application using JDBC ?



A simple Java application showing how to query a table in a database i.e performing a delete 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 "customer". Run the create query stated below -

CREATE TABLE customer (
   'First Name' varchar(30) ,
   'Last Name' varchar(30) ,
   'E-Mail' varchar(45) ,
   'City' varchar(30) ,
   'password' varchar(30) NOT NULL,
   PRIMARY KEY ('password')
 ) 



4. Populate the table user with some data (of your own), if not run the four insert queries stated below -

insert into customer () values ('Jonty','Magic','jonty@magic.com','Pune','123456');

insert into customer () values ('Java','Sun','java@sun.com','New York','456');

insert into customer () values ('Jesse','lool','jesse@lool.com','Jamaica','23456');

insert into customer () values ('Cameroon','Black','cameroon@black.com','Sydney','34');



5. Create a Java Class. It will perform necessary insert query. 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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DeleteJdbcQuery {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 static String query = null;
 String url = null;
 String username = null;
 String password = null;

 public static void main(String[] args) {

  DeleteJdbcQuery djq = new DeleteJdbcQuery();
  djq.createConnection();

  query = "delete from customer where First_Name='Jonty';";

  djq.executeQuery(query);

  query = "delete from customer where First_Name='Java';";

  djq.executeQuery(query);

  djq.release();

 }

 private void release() {

  try {    
   statement.close();
   connection.close();
  }
  catch (SQLException se) {

   se.printStackTrace();
  } 


 }

 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(String query) {

  try {

   statement = connection.createStatement();
   statement.execute(query);

  }
  catch (SQLException e) {

   e.printStackTrace();

  }
 } 
}





Output after Insert query -











Output after Delete query -





How to perform update sql query in JSP and Servlets using JDBC ?




A simple web application showing how to query a table in a database i.e performing a update query using JDBC

Steps for querying a Database using JDBC -

1. Download the driver jar from Internet and place it in WEB-INF/lib folder of your Web 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 "customer". Run the create query stated below -

 CREATE TABLE customer (
   'First Name' varchar(30) ,
   'Last Name' varchar(30) ,
   'E-Mail' varchar(45) ,
   'City' varchar(30) ,
   'password' varchar(30) NOT NULL,
   PRIMARY KEY ('password')
 ) 



4. Populate the table user with some data (of your own), if not run the four insert queries stated below -

insert into customer () values ('Jonty','Magic','jonty@magic.com','Pune','123456');

insert into customer () values ('Java','Sun','java@sun.com','New York','456');

insert into customer () values ('Jesse','lool','jesse@lool.com','Jamaica','23456');

insert into customer () values ('Cameroon','Black','cameroon@black.com','Sydney','34');



5. Create a Servlet. It will perform necessary update query. The code for servlet 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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UpdateJdbcQueryServlet")
public class UpdateJdbcQueryServlet extends HttpServlet {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 static String query = null;
 String url = null;
 String username = null;
 String password = null;

 public void init(ServletConfig config) throws ServletException {

  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();
  }

 }


 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  doPost(request, response);

 }


 protected void doPost(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  query = "update customer set Last_Name='Smarty' , First_Name='John' , " +
    "Email='john@smarty.com' where First_Name='Jonty';";

  executeQuery(query);

  query = "update customer set Last_Name='Tommy' , First_Name='Hil' , " +
    "Email='hil@tommy.com' where First_Name='Jesse';";

  executeQuery(query);


  query = "update customer set Last_Name='Tendulkar' , First_Name='Sachin' , " +
    "Email='sachin@god.com' where First_Name='Cameroon';";

  executeQuery(query);

  query = "update customer set Last_Name='Sharp' , First_Name='See' , " +
    "Email='see@sharp.com' where First_Name='Java';";

  executeQuery(query);

 }

 private void executeQuery(String query) {

  try {

   statement = connection.createStatement();
   statement.execute(query);

  }
  catch (SQLException e) {

   e.printStackTrace();

  }
 } 

 @Override
 public void destroy() {
  try {    
   statement.close();
   connection.close();
  }
  catch (SQLException e) {

   e.printStackTrace();
  } 

 }

}




Output after Insert query -











Output after Update query -




How to perform update sql query in a Java application using JDBC ?



A simple Java application showing how to query a table in a database i.e performing a update 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 "customer". Run the create query stated below -

CREATE TABLE customer (
   'First Name' varchar(30) ,
   'Last Name' varchar(30) ,
   'E-Mail' varchar(45) ,
   'City' varchar(30) ,
   'password' varchar(30) NOT NULL,
   PRIMARY KEY ('password')
 ) 



4. Populate the table user with some data (of your own), if not run the four insert queries stated below -

insert into customer () values ('Jonty','Magic','jonty@magic.com','Pune','123456');

insert into customer () values ('Java','Sun','java@sun.com','New York','456');

insert into customer () values ('Jesse','lool','jesse@lool.com','Jamaica','23456');

insert into customer () values ('Cameroon','Black','cameroon@black.com','Sydney','34');



5. Create a Java Class. It will perform necessary insert query. The code for Java class is shown below -


package com.hubberspot.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class UpdateJdbcQuery {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 static String query = null;
 String url = null;
 String username = null;
 String password = null;

 public static void main(String[] args) {

  UpdateJdbcQuery ujq = new UpdateJdbcQuery();
  ujq.createConnection();

  query = "update customer set Last_Name='Smarty' , First_Name='John' , " +
    "Email='john@smarty.com' where First_Name='Jonty';";

  ujq.executeQuery(query);

  query = "update customer set Last_Name='Tommy' , First_Name='Hil' , " +
    "Email='hil@tommy.com' where First_Name='Jesse';";

  ujq.executeQuery(query);


  query = "update customer set Last_Name='Tendulkar' , First_Name='Sachin' , " +
    "Email='sachin@god.com' where First_Name='Cameroon';";

  ujq.executeQuery(query);

  query = "update customer set Last_Name='Sharp' , First_Name='See' , " +
    "Email='see@sharp.com' where First_Name='Java';";

  ujq.executeQuery(query);

  ujq.release();

 }

 private void release() {

  try {    
   statement.close();
   connection.close();
  }
  catch (SQLException se) {

   se.printStackTrace();
  } 


 }

 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(String query) {

  try {

   statement = connection.createStatement();
   statement.execute(query);

  }
  catch (SQLException e) {

   e.printStackTrace();

  }
 } 
}





Output after Insert query -











Output after Update query -


How to perform insert sql query in JSP and Servlets using JDBC ?



A simple web application showing how to query a table in a database i.e performing a insert query using JDBC

Steps for querying a Database using JDBC -

1. Download the driver jar from Internet and place it in WEB-INF/lib folder of your Web 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 "customer". Run the create query stated below -

CREATE TABLE customer (
  'First Name' varchar(30) ,
  'Last Name' varchar(30) ,
  'E-Mail' varchar(45) ,
  'City' varchar(30) ,
  'password' varchar(30) NOT NULL,
  PRIMARY KEY ('password')
)  




4. Create a Servlet. It will perform necessary insert query. The code for servlet 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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/InsertJdbcQueryServlet")
public class InsertJdbcQueryServlet extends HttpServlet {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 static String query = null;
 String url = null;
 String username = null;
 String password = null;

 public void init(ServletConfig config) throws ServletException {

  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();
  }

 }


 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  doPost(request, response);

 }


 protected void doPost(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  query = "insert into customer () values " +
    "('Jonty','Magic','jonty@magic.com','Pune','123456');";
  executeQuery(query);

  query = "insert into customer () values " +
    "('Java','Sun','java@sun.com','New York','456');";
  executeQuery(query);

  query = "insert into customer () values " +
    "('Jesse','lool','jesse@lool.com','Jamaica','23456');";
  executeQuery(query);

  query = "insert into customer () values " +
    "('Cameroon','Black','cameroon@black.com','Sydney','34');";
  executeQuery(query);

 }

 private void executeQuery(String query) {

  try {

   statement = connection.createStatement();
   statement.execute(query);

  }
  catch (SQLException e) {

   e.printStackTrace();

  }
 } 

 @Override
 public void destroy() {
  try {    
   statement.close();
   connection.close();
  }
  catch (SQLException e) {

   e.printStackTrace();
  } 

 }

}





Output of the program :



How to perform insert sql query in a Java application using JDBC ?



A simple Java application showing how to query a table in a database i.e performing a insert 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 "customer". Run the create query stated below -

CREATE TABLE customer (
  'First Name' varchar(30) ,
  'Last Name' varchar(30) ,
  'E-Mail' varchar(45) ,
  'City' varchar(30) ,
  'password' varchar(30) NOT NULL,
  PRIMARY KEY ('password')
)  




4. Create a Java Class. It will perform necessary insert query. 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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertJdbcQuery {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 static String query = null;
 String url = null;
 String username = null;
 String password = null;

 public static void main(String[] args) {

  InsertJdbcQuery ijq = new InsertJdbcQuery();
  ijq.createConnection();
  query = "insert into customer () 
values ('Jonty','Magic','jonty@magic.com','Pune','123456');";
  ijq.executeQuery(query);

  query = "insert into customer () 
values ('Java','Sun','java@sun.com','New York','456');";
  ijq.executeQuery(query);

  query = "insert into customer () 
values ('Jesse','lool','jesse@lool.com','Jamaica','23456');";
  ijq.executeQuery(query);

  query = "insert into customer () 
values ('Cameroon','Black','cameroon@black.com','Sydney','34');";
  ijq.executeQuery(query);

  ijq.release();

 }

 private void release() {

  try {    
   statement.close();
   connection.close();
  }
  catch (SQLException se) {

   se.printStackTrace();
  } 


 }

 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(String query) {

  try {

   statement = connection.createStatement();
   statement.execute(query);

  }
  catch (SQLException e) {

   e.printStackTrace();

  }
 } 
}



Output of the program :



How to perform create sql query in JSP and Servlets using JDBC ?



A simple web application showing how to query a table in a database i.e performing a create query using JDBC

Steps for querying a Database using JDBC -

1. Download the driver jar from Internet and place it in WEB-INF/lib folder of your Web 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 Servlet. It will perform necessary create query. The code for servlet 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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CreateJdbcQueryServlet")
public class CreateJdbcQueryServlet extends HttpServlet {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 String query = null;
 String url = null;
 String username = null;
 String password = null;

 public void init(ServletConfig config) throws ServletException {

  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();
  }

 }


 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  doPost(request, response);

 }


 protected void doPost(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {

  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();

  query = "create table customer " +      
    "(First_Name varchar(20) NOT NULL,"+    
    "Last_Name varchar(30) NOT NULL,"+
    "Email varchar(50) NOT NULL,"+
    "City varchar(30) NOT NULL,"+    
    "password varchar(30) NOT NULL PRIMARY KEY "+    
    ");";

  try {

   statement = connection.createStatement();
   statement.execute(query);

  }
  catch (SQLException e) {

   e.printStackTrace();
  }
 }
  
 @Override
 public void destroy() {
  try {    
   statement.close();
   connection.close();
  }
  catch (SQLException e) {

   e.printStackTrace();
  } 

 }


}





How to connect MySql Database using JDBC API in Java ?.

A Simple Program demonstrating how to connect MySql Database using JDBC API in Java

package com.hubberspot.jdbc.example;

import java.sql.*;
import java.io.*;

public class JdbcConnectivity
{
  public static void main(String[] args) throws SQLException
  {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    String userName = "root";
    String password = "sa";
    String url = "jdbc:mysql://localhost:3306/links";
    try
    {
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection 
                            (url, userName, password);
      
      if(conn!=null)
        System.out.println("Connection successful..");
      
      stmt = conn.createStatement();
      rs = stmt.executeQuery("Select * from student");
      
      while(rs.next())
      {
       System.out.print("Roll Number = " + rs.getInt(3));
       System.out.print(" First Name = " + rs.getString(1));
       System.out.println(" Last Name = " + rs.getString(2));
      }
      
      conn.close();
    
    }
    catch(Exception e) 
    {
       System.out.println(e);}
    }
}    


Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot