//Insert Record into table using PreparesStatement in JDBC
package com.iton;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MainApp2 {
public static void main(String[] args) {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ramakrishna","root","root");
String query="insert into emp values(?,?)";
PreparedStatement pstmt=con.prepareStatement(query);
pstmt.setInt(1,25);
pstmt.setString(2,"jamesGosling");
pstmt.executeUpdate();
System.out.println("+++Record inserted successfully+++");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//Update Record/Records in the table using PreparesStatement in JDBC
package com.iton;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MainApp2 {
public static void main(String[] args) {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ramakrishna","root","root");
String query="update emp set name=? where no=?";
PreparedStatement pstmt=con.prepareStatement(query);
pstmt.setString(1,"java");
pstmt.setInt(2,25);
pstmt.executeUpdate();
System.out.println("+++Record updated successfully+++");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//Delete Record/Records in the table using PreparesStatement in JDBC
package com.iton;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class MainApp2 {
public static void main(String[] args) {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ramakrishna","root","root");
String query="delete from emp where no=?";
PreparedStatement pstmt=con.prepareStatement(query);
pstmt.setInt(1,25);
int count=pstmt.executeUpdate();
System.out.println("+++"+count+" Records deleted successfully+++");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//Retrieve Record/Records in the table using PreparesStatement in JDBC
package com.iton;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MainApp2 {
public static void main(String[] args) {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ramakrishna","root","root");
String query="select * from emp where no=?";
PreparedStatement pstmt=con.prepareStatement(query);
pstmt.setInt(1,26);
ResultSet rs=pstmt.executeQuery();
while(rs.next()) {
System.out.print("No:"+rs.getInt("no"));
System.out.println(" Name:"+rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}