Introduction

In this blog we will know how to insert records from database using JDBC (Java Database Connectivity) in the console window.
Here we use Type-1 driver (JDBC-ODBC bridge)

Creation of dsn(database source name) for Oracle

Start-Control panel- Administrative Tools- Data Sources (ODBC)-go to system DSN tab-click add button-select a driver for which you want to set up a data source (for Oracle- Oracle in XE)-select it and click finish-give any name in the data source name textbox-then click ok button.
Note: - Here Username=system, Password=pintu and Dsn name=dsn1

Table Creation

Create table employee (empno int,empname varchar(50),sal int)
Example:- To insert record into a table
  1. /*To insert record into a table by using Statement*/
  2. import java.sql.*;
  3. import java.util.*;
  4. public class insert
  5. {
  6. public static void main(String args[]) throws Exception
  7. {
  8. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  9. Connection con=DriverManager.getConnection("jdbc:odbc:dsn1","system","pintu");
  10. Scanner sc=new Scanner(System.in);
  11. System.out.print("Enter the Employee Number :");
  12. int x=sc.nextInt();
  13. System.out.print("Enter the Employee Name : ");
  14. String y=sc.next();
  15. System.out.print("Enter the Employee's salary : ");
  16. int z=sc.nextInt();
  17. Statement stmt=con.createStatement();
  18. stmt.executeUpdate("insert into employee(empno,empname,sal) values("+x+",'"+y+"',"+z+")");
  19. System.out.println("Record Successfully Inserted...");
  20. con.close();
  21. }
  22. }

Compile

Javac insert.java
Java insert