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");
}
}
当我运行此程序时,在输入信息后,它会显示以下错误:
线程中的异常" main" java.sql.SQLException:[Oracle] [ODBC] [Ora] ORA-00984:这里不允许列 at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source) at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source) at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source) at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source) 在SQL1.H.main(H.java:30)
有人可以解释为什么会发生此异常吗?
答案 0 :(得分:4)
使用Prepare stmt而不是传递内联参数。还在insert语句中提供列名:
// 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();
答案 1 :(得分:0)
对于插入(对于所有DML),您必须使用executeUpdate()
方法。
答案 2 :(得分:-3)
您忘记了varchar列的单引号。像这样使用它
sql = "insert into employee values(" + id + ",'" + fName + "','" + lName + "'," + age + ")";