Вы можете попробовать этот подход
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/first";
String user="root";
String pass="****";
con=DriverManager.getConnection(url,user,pass);
String query="select name from sample_t where rollno=?";
pstmt=con.prepareStatement(query);
System.out.println("Enter user id : ");
pstmt.setInt(1, sc.nextInt());
rs=pstmt.executeQuery();
//Process the result
if(rs.next())
{
System.out.println("Roll No. : " +rs.getInt(1));
}
//closing connections
sc.close();
pstmt.close();
rs.close();
con.close();
}
catch (Exception e)
{`
e.printStackTrace();
}