英文:
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);
//...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论