JDBC - Insert records into table using PreparedStatement
For Explanation watch Video :
Code::
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Test {
private static final String query = "insert into test1 values(?,?)";
public static void main(String[] args)throws Exception{
//generate connection
try(Scanner scn = new Scanner(System.in)){
System.out.println("Enter The eid: ");
int eid = scn.nextInt();
System.out.println("Enter employee name: ");
String ename = scn.next();
try(Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","tiger");
PreparedStatement ps = con.prepareStatement(query);){
ps.setInt(1, eid);
ps.setString(2, ename);
int count = ps.executeUpdate();
if(count==0) {
System.out.println("Record Not Inserted");
}else {
System.out.println("Record Inserted");
}
}
}
catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
}
Comments
Post a Comment