-
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
Lecture1.4
-
Lecture1.5
-
Lecture1.6
-
Lecture1.7
-
Lecture1.8
-
Lecture1.9
-
Lecture1.10
-
Lecture1.11
-
Lecture1.12
-
Lecture1.13
-
Lecture1.14
-
Insert Records-PreparedStatement Example
Create a sample database table in MySQL with example content via the following SQL statement.
[php]
CREATE TABLE EMPLOYEE (
ID INT NOT NULL,
EMP_NAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(30),
DATEOFBIRTH DATE NOT NULL,
PRIMARY KEY (ID));
)
[/php]
Below example uses PrepareStatement method to create PreparedStatement. It also uses setInt, setString and setDate methods of PreparedStatement to set parameters of PreparedStatement.
[php]
package com.tech2our.jdbc;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PreparedStatementExample {
public static void main(String[] args) {
System.out.println("Insert records example using prepared statement!");
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/jdbctutorial","root","tech2our");
try {
String sql = "INSERT INTO EMPLOYEE (ID,EMP_NAME,EMAIL,DATEOFBIRTH) VALUES(?,?,?,?)";
PreparedStatement preparedStatement = con.prepareStatement(sql);
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Employee code(Number):");
int empCode = Integer.parseInt(bf.readLine());
preparedStatement.setInt(1, empCode);
System.out.println("Enter Employee Name:");
String empName = bf.readLine();
preparedStatement.setString(2, empName);
System.out.println("Enter Employee EMAIL:");
String empEmail = bf.readLine();
preparedStatement.setString(3, empEmail);
System.out.println("Enter Employee Date of Birth(dd-mm-yyyy):");
String empDOB = bf.readLine();
SimpleDateFormat sdm = new SimpleDateFormat("dd-MM-yyyy");
Date dt = sdm.parse(empDOB);
preparedStatement.setDate(4, new java.sql.Date(dt.getTime()));
int count = preparedStatement.executeUpdate();
System.out.println(count + "row(s) affected");
con.close();
} catch (SQLException s) {
System.out.println("SQL statement is not executed!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
[/php]