Introduction
In this blog, we will know how to insert records in a table
using PreparedStatement of 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
Ex:- To insert a record into a table by using PreparedStatement
Table Creation
- create table employee(empno int,empname varchar(50),sal int)
- import java.sql.*;
- import java.util.*;
- public class prepareDemo
- {
- public static void main(String args[]) throws Exception
- {
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- Connection con = DriverManager.getConnection("jdbc:odbc:dsn1", "system", "pintu");
- PreparedStatement pstmt = con.prepareStatement("insert into employee(empno,empname,sal) values(?,?,?)");
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter the Employee Number : ");
- int empno = sc.nextInt();
- System.out.print("Enter the Employee Name : ");
- String empname = sc.next();
- System.out.print("Enter the Employee's salary : ");
- int sal = sc.nextInt();
- pstmt.setInt(1, empno);
- pstmt.setString(2, empname);
- pstmt.setInt(3, sal);
- pstmt.executeUpdate();
- System.out.println("record inserted");
- con.close();
- }
- }
Compile
Javac
prepareDemo.java
Java
prepareDemo