I want to sort an SQL statement based on user input, using a preparedStatement
. I have a student
table with three columns id
, name
and age
, and the user can choose which column the results are sorted by.
try
{
System.out.println("Enter the column name to sort the data with");
Scanner sc=new Scanner(System.in);
String str=sc.next();
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","SYSTEM","SYSTEM");
if(str.equals("id"))
{
String query="select * from STUDENT order by ?";
PreparedStatement pst=con.prepareStatement(query);
pst.setString(1,"id");
pst.executeUpdate();
}
if(str.equals("name"))
{
String query="select * from STUDENT order by ?";
PreparedStatement pst=con.prepareStatement(query);
pst.setString(1,"name");
pst.executeUpdate();
}
if(str.equals("age"))
{
String query="select * from STUDENT order by ?";
PreparedStatement pst=con.prepareStatement(query);
pst.setString(1,"age");
pst.executeUpdate();
}
}
catch(Exception e)
{
e.printStackTrace();
}