The following java program is an example of inserting multiple records in a database.
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
class InsertMultipleRec {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "kiru");
PreparedStatement pst = con.prepareStatement("INSERT INTO DEPT VALUES(?,?,?)");
java.util.Scanner scanner = new java.util.Scanner(System.in);
String choice = null;
do {
System.out.println("enter dno,dname and city");
pst.setInt(1, scanner.nextInt());
pst.setString(2, scanner.next());
pst.setString(3, scanner.next());
System.out.println(pst.executeUpdate() + " rec is inserted");
System.out.println("do you want to insert another record..? (Y/N)");
choice = scanner.next();
} while (choice.equalsIgnoreCase("Y"));
scanner.close();
pst.close();
con.close();
}
}
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
class InsertMultipleRec {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "kiru");
PreparedStatement pst = con.prepareStatement("INSERT INTO DEPT VALUES(?,?,?)");
java.util.Scanner scanner = new java.util.Scanner(System.in);
String choice = null;
do {
System.out.println("enter dno,dname and city");
pst.setInt(1, scanner.nextInt());
pst.setString(2, scanner.next());
pst.setString(3, scanner.next());
System.out.println(pst.executeUpdate() + " rec is inserted");
System.out.println("do you want to insert another record..? (Y/N)");
choice = scanner.next();
} while (choice.equalsIgnoreCase("Y"));
scanner.close();
pst.close();
con.close();
}
}
Oracle Express database is used in this example. If the choice is either "y" or "Y" ,it asks for inserting another record or else the program gets terminated. The sample output of this program is shown in the below fig.
0 comments:
Post a Comment