Prepared statements
Database : College
Table name : Department
Fields : DeptCode INT & DeptName VARCHAR(20)

// JDBC
import java.sql.*;
import java.util.*;
class JDBC_Demo
{
public
static void main(String as[])
{
Scanner sc = new Scanner(System.in);
try
{
Connection conc =
DriverManager.getConnection("jdbc:mysql://localhost:3306/College","root",
"JP@2026");
System.out.println("Database
Connected");
PreparedStatement ps =
conc.prepareStatement("Select * from Department where DeptCode=?");
for(int i=0;i<3;i++)
{
System.out.print("Enter
Department Code to search : ");
int dc = sc.nextInt();
ps.setInt(1,dc);
ResultSet rs = ps.executeQuery();
if(rs.next())
System.out.println("Deptartment
= "+rs.getString(2));
else
System.out.println("No
Deptartment found.");
}
conc.close();
}
catch(SQLException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println("EOP");
}
}
}
Sample Output:
>javac JDBC_Demo.java
>java JDBC_Demo
Database Connected
Enter Department Code to
search : 205
Deptartment = IT
Enter Department Code to
search : 105
Deptartment = EEE
Enter Department Code to
search : 1234
No Deptartment found.
EOP
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu