Write a program to insert student records to database using Prepared Statement.
import java.sql.*;
import java.util.Scanner;
public class PreparedStatement {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/College", "root", "");
PreparedStatement ps = conn.prepareStatement("insert into StudentDetail(RollNo, Name, Branch)values(?,?,?)");
System.out.print("Enter RollNo: ");
int rollno = sc.nextInt();
sc.nextLine();
System.out.print("Enter Name: ");
String name = sc.nextLine();
System.out.print("Enter Branch: ");
String branch = sc.nextLine();
ps.setInt(1, rollno);
ps.setString(2, name);
ps.setString(3, branch);
int i = ps.executeUpdate();
System.out.println(i + " row affected");
ps.close();
conn.close();
}
catch(Exception ex) {
System.out.println(ex);
}
}
}
0 Comments