我正在通过JDBC编写方法来创建表和要在触发器中调用的序列,我想设置一个id列,该ID列在表上的每次插入之前都会自动递增。我在DAO中成功构建了createTable方法和createSequence方法,但是当我运行该方法以创建触发器时,我得到了java.sql.SQLException:在索引处缺少IN或OUT参数:1
public void createTrigger() {
PreparedStatement ps;
StringBuilder queryTrigger = new StringBuilder();
queryTrigger.append("CREATE OR REPLACE TRIGGER ");
queryTrigger.append(Tables.getInstance().getName() + "_INSERTED\n");
queryTrigger.append("BEFORE INSERT ON " + Tabelle.getInstance().getName());
queryTrigger.append("\nFOR EACH ROW\n");
queryTrigger.append("BEGIN\n");
queryTrigger.append("SELECT " + Tables.getInstance().getName() + "SEQ.NEXTVAL\n");
queryTrigger.append("INTO :new.id\n");
queryTrigger.append("FROM dual;\n ");
queryTrigger.append("END;\n");
queryTrigger.append("/\n");
queryTrigger.append("ALTER TRIGGER " +Tabelle.getInstance().getName() + "_INSERTED ENABLE\n");
queryTrigger.append("/\n");
String stringQueryTrigger = queryTrigger.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(stringQueryTrigger);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);}
在这里,即使我不创建表,实际上也能正常工作 用参数化的“?”写经典行为prepareStatement.setString(index,String)
public void createTable(Columns c) {
PreparedStatement ps;
StringBuilder query = new StringBuilder();
query.append("CREATE TABLE " + Tabelle.getInstance().getName() + "(");
query.append(Columns.getInstance().getColumnName() + " ");
query.append(Columns.getInstance().getDataType());
if(Columns.getInstance().isNullOrNot() == true) {
query.append(" NOT NULL");
}
else {
query.append("");
}
if(Columns.getInstance().isPrimaryKeyOrNot() == true) {
query.append(" PRIMARY KEY)");
}
else {
query.append(")");
}
String queryToString = query.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(queryToString);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);
}
//编辑
结果足以用一个简单的Statement替换PreparedStatement,摆脱索引机制并让DB接受查询
答案 0 :(得分:0)
我建议在oracle中创建一个可用于所有id的自动递增序列,只需将字符串id.NextVal添加到字符串查询中
我的意思是:
Oracle中的Rem创建序列
CREATE SEQUENCE ID
START BY 1
INCREMENT 1
//在Java中执行查询
String query = "INSERT INTO TABLE VALUES(ID.NEXTVAL);" ;
//其余代码