在Java程序中将非硬编码值(变量)放入Oracle SQL选择语句的正确语法。

huangapple go评论76阅读模式
英文:

Right syntax to put non hard coded values(variables) in oracle sql select statement in java program

问题

我在下面的代码中遇到了以下错误。 java.sql.SQLSyntaxErrorException: ORA-00904: "ROLLNO":无效标识符。我尝试在选择语句中也使用了roll_no='rollNo',但没有起作用。我想知道where子句中的正确语法。roll_no是一个数据类型为int的students表中的列。rollNo是在方法中传递的另一个int值。

public boolean authenticate(int rollNo,String password) {
  String sql = "SELECT password FROM students WHERE roll_no=" + rollNo; //这个语句导致错误
  ResultSet rs=stmt.executeQuery(sql);
}
英文:

I got the following error with the below code. java.sql.SQLSyntaxErrorException: ORA-00904: "ROLLNO": invalid identifier . I tried roll_no='rollNo' as well in the select statement but did not work. I would like to know the right syntax in the where clause. roll_no is a column in students of datatype int. rollNo is another int value passed in the method.

public boolean authenticate(int rollNo,String password) {
  String sql = "SELECT password FROM students where roll_no=rollNo"; //this statement giving error
  ResultSet rs=stmt.executeQuery(sql);
}

答案1

得分: 3

使用PreparedStatement可以使事情更容易,并且可以避免SQL注入。

public boolean authenticate(int rollNo, String password) {
    String sql = "SELECT password FROM students WHERE roll_no=?";
    PreparedStatement pstmt = conn.prepareStatement(sql);// 这里的conn是Connection对象
    pstmt.setInt(1, rollNo);
    ResultSet rs = pstmt.executeQuery();
    //...
}
英文:

Use PreparedStatement to make things easier and also to avoid SQL injection.

public boolean authenticate(int rollNo,String password) {
	String sql = "SELECT password FROM students where roll_no=?";
	PreparedStatement pstmt = conn.prepareStatement(sql);// Where conn is Connection object
	pstmt.setInt(1, rollNo);
	ResultSet rs = pstmt.executeQuery(sql);
	//...
}

huangapple
  • 本文由 发表于 2020年5月5日 18:48:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/61611341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定