jbn6972

Untitled

Jan 23rd, 2022 (edited)
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1.  
  2. // Java Program to Establish Connection in JDBC
  3.  
  4. // Importing database
  5. importjava.sql.*;
  6. // Importing required classes
  7. importjava.util.*;
  8.  
  9. // Main class
  10. class Main {
  11.  
  12.     // Main driver method
  13.     public static void main(String a[])
  14.     {
  15.  
  16.         // Creating the connection using Oracle DB
  17.         // Note: url syntax is standard, so do grasp
  18.         String url = "jdbc:oracle:thin:@localhost:1521:xe";
  19.  
  20.         // Usernamer and password to access DB
  21.         // Custom initialization
  22.         String user = "system";
  23.         String pass = "12345";
  24.  
  25.         // Entering the data
  26.         Scanner k = new Scanner(System.in);
  27.  
  28.         System.out.println("enter name");
  29.         String name = k.next();
  30.  
  31.         System.out.println("enter roll no");
  32.         int roll = k.nextInt();
  33.  
  34.         System.out.println("enter class");
  35.         String cls = k.next();
  36.  
  37.         // Inserting data using SQL query
  38.         String sql = "insert into student1 values('" + name
  39.                      + "'," + roll + ",'" + cls + "')";
  40.  
  41.         // Connection class object
  42.         Connection con = null;
  43.  
  44.         // Try block to check for exceptions
  45.         try {
  46.  
  47.             // Registering drivers
  48.             DriverManager.registerDriver(
  49.                 new oracle.jdbc.OracleDriver());
  50.  
  51.             // Reference to connection interface
  52.             con = DriverManager.getConnection(url, user,
  53.                                               pass);
  54.  
  55.             // Creating a statement
  56.             Statement st = con.createStatement();
  57.  
  58.             // Executing query
  59.             int m = st.executeUpdate(sql);
  60.             if (m == 1)
  61.                 System.out.println(
  62.                     "inserted successfully : " + sql);
  63.             else
  64.                 System.out.println("insertion failed");
  65.  
  66.             // Closing the connections
  67.             con.close();
  68.         }
  69.  
  70.         // Catch block to handle exceptions
  71.         catch (Exception ex) {
  72.             // Display message when exceptions occurs
  73.             System.err.println(ex);
  74.         }
  75.     }
  76. }
Add Comment
Please, Sign In to add comment