I have a below query, which needs to select a row by using a column as key and return generated keys.
INSERT INTO t_tpms_cc_request
(process_identifier,
request_source_id,
amount,
etc_account_id,
retry_count,
status,
store_identifier,
version_no,
next_process_time,
composite_transaction_id,
payment_id,
processed_time,
replenishment_id,
pay_type,
agency_id,
response_code,
file_id,
request_date,
auth_file_id,
auth_date_time,
merc_file_id,
merc_date_time,
cc_num,
cc_expiration_date,
merchant_id,
ext_sys_ref,
encrypt_cc_number,
cc_month_cd,
cc_year_cd,
orig_txn_ref,
auth_code,
avs_code,
cvv_code)
SELECT CC.process_identifier,
CC.request_source_id,
CC.amount,
CC.etc_account_id,
CC.retry_count,
CC.status,
CC.store_identifier,
CC.version_no,
CC.next_process_time,
CC.composite_transaction_id,
CC.payment_id,
CC.processed_time,
CC.replenishment_id,
CC.pay_type,
CC.agency_id,
CC.response_code,
CC.file_id,
CC.request_date,
CC.auth_file_id,
CC.auth_date_time,
CC.merc_file_id,
CC.merc_date_time,
CC.cc_num,
CC.cc_expiration_date,
CC.merchant_id,
CC.ext_sys_ref,
CC.encrypt_cc_number,
CC.cc_month_cd,
CC.cc_year_cd,
CC.orig_txn_ref,
CC.auth_code,
CC.avs_code,
CC.cvv_code
FROM t_tpms_cc_request CC
WHERE CC.order_id = ?
And, I have wrriten a below java code to do this:
String key[] = {"order_id"};
DataSource ds = null;
Connection con = null;
ResultSet rs = null;
try {
ds = jdbcTemplate.getDataSource();
con = ds.getConnection();
PreparedStatement ps =
con.prepareStatement(insertCCRequest.trim(), key);
ps.setString(1, OrderId);
int i= ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
return rs.getString(1);
}
} catch (SQLException e) {
logger.debug("SQL exception in RebillDao.insertCCrequest()
method..!! ");
logger.debug("Exception cause: "+e.getMessage());
e.printStackTrace();
throw e;
}
finally {
if(con!=null){
con.close();
}
}
return "";
When i run this, I get below exception:
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
Please tell me the ways to fix this.
Also, Using JDk 1.6 and ojdbc6-11.2.0.4.jar
I suspect that when you use generated keys with a prepared statement, the Oracle JDBC driver adds the RETURNING INTO clause to the INSERT statement, and that the JDBC driver is too dim to realise that the RETURNING INTO clause can't be used with INSERT INTO ... SELECT ... statements. I get the same ORA-00933 error if I attempt to run an INSERT INTO ... SELECT ... RETURNING ... statement.
What you could try instead is a PL/SQL block where we fetch the 'old' row into a record and then use an INSERT ... VALUES statement with a RETURNING_INTO clause to insert the values into the 'new' row:
DECLARE
l_row t_tpms_cc_request%ROWTYPE;
BEGIN
SELECT * INTO l_row FROM t_tpms_cc_request WHERE order_id = ?;
INSERT INTO t_tpms_cc_request (some_column, some_other_column, ...)
VALUES (l_row.some_column, l_row.some_other_column, ...)
RETURNING order_id INTO ?;
END;
As we're returning values from this, we need to prepare this as a CallableStatement instead of a PreparedStatement, and we need to register parameter 2 as an out parameter. We can then use this out parameter, instead of the getGeneratedKeys() method you're using at the moment, to return the generated key value.
Clearly this approach is Oracle-specific and won't work on other databases. I don't know how much of an issue database portability is to you, nor whether you can return generated keys from an INSERT INTO ... SELECT ... statement in other databases.
Suppose that I am implementing a query in MySQL say
Create Database newdb;
then the database responds the result
database created in 0.05 sec
Now my question is how to get this message in a Java program using JDBC?
The following code works for me
try (Statement s = conn.createStatement()) {
s.execute("SET PROFILING=1;");
s.execute("CREATE DATABASE newdb;");
try (ResultSet rs = s.executeQuery("SHOW PROFILES;")) {
rs.next();
System.out.printf(
" Statement: %s%nExecution time: %f seconds.%n",
rs.getString("Query"),
rs.getDouble("Duration"));
}
s.execute("SET PROFILING=0;");
}
The console output is
Statement: CREATE DATABASE newdb
Execution time: 0.002014 seconds.
No you cannot do that. Not at least with JDBC. All you can do is -
Class.forName(jdbcDriver);
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=");
Statement statement = connection .createStatement();
int result = statement.executeUpdate("CREATE DATABASE IF NOT EXISTS" + dbName)
and you will get result as 0.
Note that when the return value for executeUpdate is 0, it can mean one of two things:
The statement executed was an update statement that affected zero rows.
The statement executed was a DDL statement.
Documentation
I am using preparedStatement to insert data. I am using its executeQuery() method which returns resultSet of data just created by the Query. But I am getting exception saying you should use statement instead of preparedStatement.
Why? What should I do to get the result set? I want to fetch the id of last inserted record which is auto generated.
Any help is appreciated.
You get that exception because you are preparing an Insert (DML) query
to retreive your auto generated key you should create you statement using the following Connection method
PreparedStatement ps = connection.prepareStatement(myQuery,Statement.RETURN_GENERATED_KEYS );
ps.executeUpdate();
ResutSet rs = ps.getGeneratedKeys();
rs.first();
int generatedKey = rs.getInt(1);
I am using preparedStatement to insert data. I am using its executeQuery()
If you are using preparedStatement for inserting then you should not use executeQuery().
Use executeUpdate()
Note
executeUpdate() return int so if you want to check whether inserted or not then do this way
if(executeUpdate()>0)
{
//do some thing
}
{
else
//do somethind
}
try
{
String sql="INSERT INTO `task`(`task`,`time`) VALUES(?,?)";
PreparedStatement stmt=this.connection.prepareStatement(sql);
stmt.setString(1, this.task);
stmt.setInt(2, this.time);
//stmt.
Boolean res= stmt.execute(sql);
}
catch(Exception e)
{
System.err.println(e);
}
ERROR:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?)' at line 1
Don't use
stmt.execute(sql);
use
stmt.execute();
to execute your PreparedStatement.
The first one you are using tries to execute the given string, which is obviously not what you want to execute due to the placeholder '?' values in it (it is a method of the java.sql.Statement interface).
The second one is a method from java.sql.PreparedStatement and executes the PreparedStatement with the values you entered through the setXXX() methods.
Also, in your case you don't need ticks in your string, you can just write
String sql="INSERT INTO task(task,time) VALUES(?,?)";
How to get how many rows updated with PreparedStatement?
.getUpdateCount() returns 0.
For executeUpdate got error:
error occurred during batching: batch must be either executed or cleared
my code:
updTrans = dataSource.getConnection().prepareStatement("update...");
updTrans.setInt(1, Integer.valueOf(transaksjonstatusid));
...
updTrans.addBatch();
upd = updTrans.executeUpdate();
You should be using PreparedStatement#executeBatch() when using batches.
...
updTrans.addBatch();
upd = updTrans.executeBatch();
It returns an int[] containing update counts of each batch.
Did you try to use:
int n = preparedStatement.executeUpdate();
Here you can find some explanations on how to use a PreparedStatement.
See The Javadoc
public int executeUpdate()
throws SQLException
Executes the SQL statement in this PreparedStatement object, which must
be an SQL INSERT, UPDATE or DELETE
statement; or an SQL statement that
returns nothing, such as a DDL
statement.
Returns:
either (1) the row count for INSERT, UPDATE, or DELETE statements
or (2) 0 for SQL statements that return nothing
Throws:
SQLException - if a database access error occurs or the SQL
statement returns a ResultSet object
getUpdateCount is meant to be used with the execute(String sql) method. You are probably doing this:
String sql = "UPDATE some_table SET somecolumn = ? WHERE someId = ?";
PreparedStatement ps = connection.prepare(sql);
ps.setString(1, val);
ps.setInt(2, id);
ps.executeUpdate();
In that case you should simply do
int rowsUpdated = ps.executeUpdate();