I use HSQLDB - Tried version 2.3.4 and 2.4.
I have this Java code:
String sqlquery = "MERGE INTO bewertung pu USING "
.concat("(VALUES ?,?,?) ")
.concat("temp (tid,jurorid,runde) ")
.concat("ON temp.tid = pu.tid and temp.jurorid=pu.jurorid and temp.runde=pu.runde ")
.concat("WHEN NOT MATCHED THEN ")
.concat("INSERT (tid,jurorid,runde) ")
.concat("VALUES (temp.tid,temp.jurorid,temp.runde)");
PreparedStatement preparedStatement = sql.getConnection().prepareStatement(sqlquery,
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setInt(1, eineBewertung.getTanzID()); //TID
preparedStatement.setInt(2, eineBewertung.getJurorID()); //JURORID
preparedStatement.setInt(3, eineBewertung.getRunde()); //RUNDE
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected == 0) {
//UPDATE
//DO SOMETHING
}else{
//INSERT
try (ResultSet rs = preparedStatement.getGeneratedKeys()) {
if (rs.next()) {
eineBewertung.setBewertungsid(rs.getInt(1));
}
}catch (SQLException ex) {
this.controller.error_ausgeben(ex);
}
}
It works. If I insert a new row I get rowsAffected = 1. I check the database and the insert worked.
But, I do not get anything back in the resultset getGeneratedKeys()
It is every time empty.
I have found some tips to replace Statement.RETURN_GENERATED_KEYS with the primary key. But this didn`t work for me.
PreparedStatement preparedStatement = sql.getConnection().prepareStatement(sqlquery,
new String[]{"BEWERTUNGSID"});
This is how I create the table:
statement.execute("create table PUBLIC.BEWERTUNG"
.concat("(BEWERTUNGSID INTEGER IDENTITY,")
.concat("TID INTEGER FOREIGN KEY REFERENCES Tanz(Tanzid),")
.concat("JURORID INTEGER not null FOREIGN KEY References JUROR(JURORID),")
.concat("RUNDE INTEGER not null,")
.concat("primary key(BEWERTUNGSID)")
.concat(")"));
Why do I not get any generated keys back? Thank you
//EDIT
If I replace my sqlquery with an insert statement it is working.
sqlquery = "INSERT INTO BEWERTUNG(TID, JURORID, RUNDE) VALUES(22, 2, 2)";
Why is merge not working in the sqlquery?
With versions of HSQLDB up to 2.4.0, generated keys are not available when inserting data using a MERGE statement. Code has been committed to allow this in the next version.
This exception is occur in mentioned section of my code:
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "Insert into ...";
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query, java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate(query);
rs = ps.getGeneratedKeys(); // Exception is here
}
while (resultset.next()) {
id = String.valueOf(resultset.getInt(1));
}
Exception:
Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement()
My purpose is inserting a new record and save the first field (id) (that is auto_increment) to variable id.
You are using the wrong execute method. Instead of the one taking a String, you should use one without a parameter. And as Chris Joslin mentioned, for INSERT it is better to use executeUpdate.
Technically a correct JDBC driver should throw an SQLException immediately when calling execute(String) or one of its siblings on a PreparedStatement, but some drivers ignore this rule.
Try ps.executeUpdate() instead of ps.execute().
Shouldn't it be:
String query = "Insert into Books(Name,ISBN,Status,Date)" +
"values( '" + name + "','" + isbn + "','" + status+ "','" + date + "' ) ";
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query,java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
rs = ps.getGeneratedKeys(); // Exception is here
}
It looks like in your first example, you do a prepare correctly, but then call the executeUpdate with the Query String again instead of just the ps.executeUpdate().
ps = con.prepareStatement(query, java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate(query);
I am trying to get the identity column returned to my java program when doing a SQL insert. I am getting the following error when running the code
Uncaught exception thrown in one of the service methods of the
servlet: Cocoon. Exception thrown : java.lang.AbstractMethodError: java/sql
/Connection.prepareStatement(Ljava/lang/String;I)Ljava/sql/PreparedStatement;
Here is the code I am running.
private void insertUserInputParameters(ReportData rptData){
UserInputParameters userParams = rptData.getUserInputData();
StringBuilder sql = new StringBuilder();
PreparedStatement pstmt = null;
ResultSet rs = null;
int userDataId = -1;
//Get a database connection.
sl = ServiceLocator.getInstance();
ds = sl.getDataSource("jdbc/collegeguide");
con = ds.getConnection();
con.setReadOnly(false);
sql.append("insert into cpgusrdtaf (statecd, addr1, addr2, city, state, ");
sql.append("zipcode, dependent, shdindic, marstatus, residency, prntatge, ");
sql.append("fincome, mincome, pincome, taxspaid, taxreturn, elig1040, ");
sql.append("gincome, pcash, inetwrth, bnetwrth, pbenefit, paddlinf, ");
sql.append("puntax, pdslcwrk, smstatus, sresidncy, studtr, stud1040, ");
sql.append("sadjinc, sincome, spincome, sdslcwrk, studtax, scash, ");
sql.append("sinvest, snetwrth, saddlinf, suntax, househld, nmbrsch, ");
sql.append("studact, studsat, schools, housing) ");
sql.append("values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ");
sql.append("?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
//This line of code is where I get the error**
pstmt = con.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
//If I remove the 'Statement.RETURN_GENERATED_KEYS' I do not get the error.**
pstmt = con.prepareStatement(sql.toString());
setStatementValues(pstmt, userParams);
pstmt.executeUpdate();
rs = pstmt.getGeneratedKeys();
if(rs.next()){
userDataId = rs.getInt(1);
}
I am not allowed to use stored procedures, so I cannot go that route. Any help would be greatly appreciated
I am using java 1.5
Thanks in advance
Doug
Assuming the arguments/parameters are balanced
(please confirm the query executes natively, and that the driver supports the RETURN_GENERATED_KEYS),
Can you try to use RETURN_GENERATED_KEYS as part of the argument to an executeUpdate call?
pstmt = con.createStatement();
pstmt.executeUpdate(sql.toString(), Statement.RETURN_GENERATED_KEYS);
EDIT:
Just read your note about using DB2. According to http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.db2.luw.apdv.java.doc%2Fsrc%2Ftpc%2Fimjcc_t0057053.html
_Restriction: For IBM Data Server Driver for JDBC and SQLJ version 3.57 or later, the following form is not valid for inserting rows into a view on a DB2® for z/OS® data server.
Connection.prepareStatement(sql-statement,
Statement.RETURN_GENERATED_KEYS);_
this way it works for me:
prepStmt = con.prepareStatement(sql, new String[]{"NameOfIDField"});
I once had a problem with an oracle db where this was not working if the table has many fields.
But the above is working for me even with 60 fields.
My JT400.jar file was an older version. I downloaded the latest jar file from sourceforge and the problem was solved.
Try with Statement
Statement st = null;
ResultSet rs = null;
st = con.createStatement();
String query = " INSERT INTO refac_folios
([usuario], [estatus]) VALUES ('" + usuario + "'," + Vista_FoliosRefacciones.ESTATUS_CREADO )" ;
Integer afectadas = st .executeUpdate( query, Statement.RETURN_GENERATED_KEYS );
if (afectadas > 0){
rs = st.getGeneratedKeys();
if (rs .next()) {
folio = rs.getInt(1);
}
rs.close();
}
st.close();
I use triggers to set PK column values of all tables so i do not do any operation about IDs in java but i need the ID after insert.
How can i get the ID?
stat.execute("INSERT INTO TPROJECT_PROCESS_GROUP(NPROJECT_ID,VDESCRIPTION) " +
"VALUES(" +
"'" + projectID + "'," +
"'" + description + "'" +
"");
Edit: Hi again I read the question, now I get an exception like 'unsupported operation'(i translated from my native language the exact english form might be different). i guess this is about oracle's support for GetGeneratedKeys? Do you know anything about this?
Solution: As mentioned in a book about callablestatements This statement can be used to execute stored procedures and functions. Unlike the PreparedStatement, most databases do not perform any preparation for the call,because it is such a simple command. The CallableStatement instances can be used toreturn the object that the stored procedure—or function, to be more exact—returned.
OracleConnection conn = null;
//OraclePreparedStatement pstat = null;
OracleCallableStatement cstat = null;
String sql = "BEGIN INSERT INTO TPROJECT P (VPROJECT_TITLE,VPROJECT_DESC) VALUES(?,?) RETURNING P.NPROJECT_ID INTO ?; END;";
try {
conn = ConnectionUtility.GetConnection();
cstat = (OracleCallableStatement)conn.prepareCall(sql);
cstat.setString(1, title);
cstat.setString(2, description);
cstat.registerOutParameter(3, OracleTypes.NUMBER);
cstat.execute();
int returnedID = cstat.getInt(3);
// System.out.println(returnedID);
conn.close();
return returnedID;
This example is how you would do it in PostgreSQL. Hopefully you can do something similar in Oracle.
This is how you get the id after INSERT INTO for auto-generated keys like serial . Important here is to provide RETURN_GENERATED_KEYS in the prepareStatement() call.
Resultset result;
PreparedStatement prep;
String query = "INSERT INTO myRel (data) VALUES (?)";
prep = db.prepareStatement(query ,Statement.RETURN_GENERATED_KEYS);
result = prep.getGeneratedKeys();
if(result.next() && result != null){
System.out.println("Key: " + result.getInt(1));
} else {
System.out.println("No, Nop nada");
}
Hope that helps someone :)
I am working with a Java prepared statement that gets data from an Oracle database. Due to some performance problems, the query uses a "virtual column" as an index.
The query looks like this:
String status = "processed";
String customerId = 123;
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = " + status + " AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(query);
ps.execute();
...
} catch (...)
This does not work. Having the function as part of the where clause causes a SQLException. I am aware of CallableStatement, and know I could use that first and then concatenate the results. However, this table uses FN_GET_CUST_ID(trans_id) as part of it's index. Is there a way to use a prepared statement with a database function as a query parameter?
Never concatenate arguments for the SQL into the String. Always use placeholders (?) and setXxx(column, value);.
You'll get the same error if you'd run the SQL in a your favorite DB tool. The problem is that Oracle can't use the function for some reason. What error code do you get?
If Customer ID is numeric keep in int not in String. Then try doing the following:
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = ? AND FN_GET_CUST_ID(trans.trans_id) = ?";
ps = conn.prepareStatement(query);
ps.setString(1, status);
ps.setInt(2, customerId);
ps.execute();
Besides other benefits of prepared statement you won't have to remember about string quotations (this causes your error most likely) and escaping of the special characters.
At the first glance, the query seems to be incorrect. You are missing an apostrophe before and after the usage of status variable (assuming that status is a varchar column).
String query = "SELECT DISTINCT trans_id FROM trans
WHERE status = '" + status + "' AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
EDIT: I am not from java background. However, as #Aron has said, it is better to use placeholders & then use some method to set values for parameters to avoid SQL Injection.