Friday, July 14, 2017

How to connect mysql database with jdbc of java in XAMMP server

5 Steps to connect to the database in java

  1. 5 Steps to connect to the database in java

    1. Register the driver class
    1. Create the connection object
    1. Create the Statement object
    1. Execute the query
    1. Close the connection object

There are 5 steps to connect any java application with the database in java using JDBC. They are as  ➝➝



Lets Describe Each Steps briefly :-

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class.

Syntax of forName() method

  1. public static void forName(String className)throws ClassNotFoundException  

Example to register the OracleDriver class

  1. Class.forName("oracle.jdbc.driver.OracleDriver");  

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

  1. 1public static Connection getConnection(String url)throws SQLException  
  2. 2public static Connection getConnection(String url,String name,String password)  
  3. throws SQLException  
    1. NOTE: By default the name is the "root "  and Password is ""  in Case of Xammp Server!!! 
    2. And the url is "Jdbc:mysql://localhost:3306/DatabaseName"
  4. Or, You can also check it in your server app.

Example to establish connection with the Oracle database

  1. Connection con=DriverManager.getConnection(url, username, password); 
  2. Note: the url ,username and password Value is Mentioned Above

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method

  1. public Statement createStatement()throws SQLException  

Example to create the statement object

  1. Statement stmt=con.createStatement(); 
  2.   Note: In all above example " throws SQLException " refers to the exception error.
  3.  So, you also can't use this  if you place your code inside the 

  1. try{
  1.     Statement stmt=con.createStatement();
  2.       }catch(Exception e){
  1.        System.out.println("the error is: "+e);
  1.       }

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

  1. public ResultSet executeQuery(String sql)throws SQLException  

Example to execute query

  1. ResultSet rs=stmt.executeQuery("select * from emp");  
  2.   
  3. while(rs.next()){  
  4. System.out.println(rs.getInt(1)+" "+rs.getString(2));  
  5. }  
  6. Note: You will disscuss briefly below in the code.


5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.

Syntax of close() method

  1. public void close()throws SQLException  

Example to close connection

  1. con.close();  
  2. Note: This fifth step is not complusory needed!!!


Read Me::

Here, i also made single insert and multiple insert in this code... You can also see  only to insert single once.

class DBSql is a whole class which consits one part of code.

Function  public void DB_con() prints all the records from the database(database name can be given as your choice) ..   Then 

 public void DB_Insert() inserts the one set of data to the database as Mentioned which are the value input by the user..  and  prints the new Updated data....   Last,

public void ins_Multiple() inserts the multiple data number of times inserts by the user...

My Suggestion is that to the viewers that: You shouldn't copy all the code and run it... Instead Of it please do code one by one and Understand the Basic Concept of JDBC...

The code Starts from here...

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ncejava.dbsql;


import java.sql.*;

import java.util.Scanner;


/**
 *
 * @author sushantjava
 */

public class DBSql {

   
 private Connection con = null;
   
 private Statement st;
   
 private ResultSet rs;

   Scanner in = new Scanner(System.in);


    public DBSql() {

       
 try {
            
          String driver = "com.mysql.jdbc.Driver";
    
        Class.forName(driver);
       
     String url = "Jdbc:mysql://localhost:3306/Database_b";
      
      String username = "root";
          
  String password = "";
    
        con = DriverManager.getConnection(url, username, password);

    
    } catch (Exception e) {

            e.printStackTrace();
    
    }
   
 }

    public void DB_con() {
     
   try {
          
 st = con.createStatement();
        
    String sql = "SELECT * FROM Book";
       
     rs = st.executeQuery(sql);
        
    System.out.println("Records from Database");
      
      System.out.println(" ID \t Name\t \t\t Author \t\t Price");
     
       while (rs.next()) {
             
  int id = rs.getInt("id");
     
           String name = rs.getString("Name");
       
         String au_name = rs.getString("Author");
         
       Double price = rs.getDouble("Prize");
               
System.out.println(id + "\t" + name + "\t" + au_name + "\t $" + price);

      
      }
        
} catch (Exception e) {
    
        e.printStackTrace();

        }

   
 }

   
 public void DB_Insert() {

       try {
          
    
   

            System.out.println("Enter the  Name of Book, Author Name , Prize of the book in dollar: ");
   
         String book_Name = in.nextLine();
           
String name = in.nextLine();
        
    Double price = in.nextDouble();
        
    st = con.createStatement();

      
      st.executeUpdate("INSERT INTO `Book` (Name,Author,Prize)values('" + book_Name + "', '" + name + "', '" + price + "' )");
        
    System.out.println("The new data are:");
       
     DB_con();
      
      con.close();
   
     } catch (Exception e) {
    
        System.err.println("Got an exception!");

           System.out.println(e);
       
 }
    
}

    public void ins_Multiple() {
     
   System.out.println("Enter the number of data to insert:");
      
  int n = in.nextInt();
        
System.out.println("Please Enter the " + n + "Datas:");
        try {
            for (int i = 1; i <= n; i++) {
                System.out.println("For Data " + i);
                System.out.println("Enter the Name of Book, Author Name, Prize of the Book in Dollar:");
                String book_Name = in.nextLine();
                String name = in.nextLine();
                Double price = in.nextDouble();
                st = con.createStatement();
                st.executeUpdate("insert into Book(Name,Author,Prize)values('" + book_Name + "','" + name + "','" + price + "')");

            }
            System.out.println("The new data are:");
            DB_con();
            con.close();

        } catch (Exception e) {
            System.err.println("Got an Exception");
            System.out.println(e);
        }

    }

}

The main class program is here...



package com.ncejava.dbsql;


import java.util.Scanner;


/**
 *
 * @author sushantjava
 */

public class DBCONNECT {

   public static void main(String[] args) {
  
      Scanner in = new Scanner(System.in);
       
 DBSql dbobj = new DBSql();
    
    System.out.println("1.TO only see  the all record!");
       System.out.println("2.TO insert the one  datas!");
  
      System.out.println("3.TO insert the multiple datas!");
   
     System.out.println("Please enter your choice!");
       
 int choice = in.nextInt();
       
 switch (choice) {
            
case 1:
                dbobj.DB_con();
    
            break;
         
   case 2:
                
dbobj.DB_Insert();
            
    break;
            
case 3:
               
 dbobj.ins_Multiple();
            
    break;
           
 default:
               
 System.out.println("Enter the correct choice!");

       
 }
   
 }


}