我想使用preparedStatement
根据用户输入对SQL语句进行排序。我有一个student
表,其中有三列id
,name
和age
,用户可以选择结果排序的列。
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();
}
答案 0 :(得分:3)
这不是预处理语句的工作原理:您正在尝试构建动态SQL,而预准备语句与绑定变量一起发出SQL语句,这些变量不能用于列名或表名。
所以你可以这样做:
String query="select * from STUDENT where some_col = ?";
PreparedStatement pst=con.prepareStatement(query);
pst.setString(1,"some_value");
pst.executeUpdate();
但不是这样:
String query="select * from ?";
PreparedStatement pst=con.prepareStatement(query);
pst.setString(1,"STUDENT");
pst.executeUpdate();
因为你不能使用变量"占位符"用于表或其他数据库对象。