insert query in java code example
Example 1: java sql statement insert example
import java.sql.*;
class JdbcInsert1 {
public static void main (String[] args) {
try {
String url = "jdbc:msql://200.210.220.1:1114/Demo";
Connection conn = DriverManager.getConnection(url,"","");
Statement st = conn.createStatement();
st.executeUpdate("INSERT INTO Customers " +
"VALUES (1001, 'Simpson', 'Mr.', 'Springfield', 2001)");
st.executeUpdate("INSERT INTO Customers " +
"VALUES (1002, 'McBeal', 'Ms.', 'Boston', 2004)");
st.executeUpdate("INSERT INTO Customers " +
"VALUES (1003, 'Flinstone', 'Mr.', 'Bedrock', 2003)");
st.executeUpdate("INSERT INTO Customers " +
"VALUES (1004, 'Cramden', 'Mr.', 'New York', 2001)");
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Example 2: 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);
}
}
}