insert into database in java code example
Example: WAP in Java to insert a record from a form to table.
import java.io.DataInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class ExPrepareStatement {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","123");
DataInputStream KB=new DataInputStream(System.in);
System.out.print("Enter Employee ID: ");
String eid=KB.readLine();
System.out.print("Enter Employee Name: ");
String en=KB.readLine();
System.out.print("Enter Employee Date Of Birth: ");
String ed=KB.readLine();
System.out.print("Enter Employee City: ");
String ec=KB.readLine();
System.out.print("Enter Employee Salary: ");
String es=KB.readLine();
PreparedStatement smt=cn.prepareStatement("insert into employees values(?,?,?,?,?)");
smt.setString(1, eid);
smt.setString(2, en);
smt.setString(3, ed);
smt.setString(4, ec);
smt.setInt(5, Integer.parseInt(es));
smt.executeUpdate();
System.out.println("Record Submitted....");
cn.close();
}
catch(Exception e){
System.out.println(e);
}
}
}