This question already has answers here:
“column not allowed here” error in INSERT statement

(7个答案)


6年前关闭。





 import java.util.Scanner;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.Statement;
      public class H {

              public static void main(String[] args) throws Exception {

                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection conn = DriverManager.getConnection("jdbc:odbc:dsn1","system","mandriva");
                   Statement stmt = conn.createStatement();
                   Scanner sc = new Scanner(System.in);

                String fName, lName, sql, input;
                 int id, age;

               do {

                  System.out.println("Enter ID");
                  id = sc.nextInt();
                  System.out.println("Enter First Name");
                  fName = sc.next();
                  System.out.println("Enter Last Name");
                  lName = sc.next();
                  System.out.println("Enter Age");
                  age = sc.nextInt();

                  sql = "insert into employee values(" + id + "," +  fName + "," +  lName + "," +  age + ")";
                 stmt.execute(sql);

              System.out.println("Do you want to insert one more(y/n)?");
              input = sc.next();
            } while("y".equals(input));

         System.out.println("done");
     }
 }


当我运行该程序时,输入信息后,它显示以下错误:

线程“主”中的异常java.sql.SQLException:[Oracle] [ODBC] [Ora] ORA-00984:此处不允许使用列
在sun.jdbc.odbc.JdbcOdbc.createSQLException(未知来源)
在sun.jdbc.odbc.JdbcOdbc.standardError(未知来源)
在sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(未知来源)
在sun.jdbc.odbc.JdbcOdbcStatement.execute(未知来源)
在SQL1.H.main(H.java:30)

谁能解释为什么发生此异常?

最佳答案

使用Prepare stmt而不是传递内联参数。还要在您的插入语句中提供列名:

// Assuming columns are: id, first_name, last_name, age
sql = "insert into employee(id, first_name, last_name, age) values(?, ?, ?, ?)";

PreparedStatement pstmt = conn.prepareStatement(sql);

pstmt.setInt(1, id);
pstmt.setString(2, fName);
pstmt.setString(3, lName);
pstmt.setInt(4, age);

pstmt.executeUpdate();

10-08 18:33