Insert - Update - Delete in JDBC ....
package jdbcpack;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
//import com.mysql.jdbc.PreparedStatement;
public class InsUpdDel
{
public static void main(String[] args)
{
Connection con=null;
PreparedStatement pstat = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
pstat = con.prepareStatement("Insert into student values(?,?,?)");
pstat.setInt(1, 2009);
pstat.setString(2, "Rohit");
pstat.setInt(3,22);
int x= pstat.executeUpdate();
if(x>=1)
System.out.println("\n successfully inserted !!");
System.out.println("\n........Updating .......");
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the sid");
int i = sc.nextInt();
pstat = con.prepareStatement("Update student set age=30 where sid=?");
pstat.setInt(1, i);
x= pstat.executeUpdate();
if(x>=1)
System.out.println("successfully updated !!");
System.out.println("\n.............Delete Statement........................");
System.out.println("Please enter the sid to be deleted !!");
i=sc.nextInt();
pstat=con.prepareStatement("delete from student where sid=?");
pstat.setInt(1,i);
x= pstat.executeUpdate();
if(x>=1)
System.out.println("successfully Deleted !!");
else
System.out.println("not found !!");
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
finally
{
try
{
con.close();
pstat.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}