"hints" formatted query output using oracle jdbc driver - oracle

Is it possible to get "hints" formatted query output using oracle jdbc driver?
example query
Select /*insert*/ * from sample_table
or
Select /*html*/ * from sample_table
looks like the stmt.executeQuer is just ignoring formatting "hints" and only return Select * results
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select /*insert*/ * from sample_table where ID = 1");
while (rs.next()) {
inserts.add(rs.getString(1));
}
} catch (SQLException e) {
log.error("SQL Error", e);
} finally {
UPD: As mentioned in the comments the /*insert*/ "hint" is specific to the SQL Developer and SQLcl clients.
I was able to get the query formatted output from SQLcl client
The eventual goal is to get formatted query output from Java code.
So re-phrasing the question: how to run query and get output through SQLcl using java ?

Related

Oracle OJDBC MERGE Statement and Generated Keys

Does Oracle ~>12 support generated keys using a Merge statement? Some sudo code..
MERGE INTO TARGET_TABLE TRG
USING (SELECT CAST(? AS NUMBER) AS ID FROM DUAL) SRC
ON (TRG.ID = SRC.ID)
WHEN MATCHED THEN UPDATE SET....
WHEN NOT MATCHED THEN
INSERT(ID....)
VALUES(MYSEQ.NEXTVAL...)
The prepared statement is set up;
try (PreparedStatement pstmt =
connection.prepareStatement(
loadStatement(sqlName, connection, getClass()), new String[] {ID})) {
...
int inserted = pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
List<Long> keys = new ArrayList<>(inserted);
while (rs.next) {
rs.getLong(1);
}
return keys;
...
I have in-memory tests where the connection uses the H2 driver running the very same SQL and PreparedStatment and that returns the generated key just fine, but Oracle does not.
Reviewing the docs it would suggest it does not?
Thanks!

JdbcTemplate queryForList changing the database order

I'm using the queryForList method to fetch the data for the following sql.
String sql = "select * from my_table ORDER BY ? ? LIMIT ?, ?";
return jdbcTemplate.queryForList(sql,new Object[]{param1,param2,
param3,param4});
I can see that the order is altered when the data is returned.To confirm, I tried using simple JDBC as follows
try {
Connection conn = jdbcTemplate.getDataSource().getConnection();
//Sample values param1 -> field1, param2 -> asc/desc, param3 -> 0, param4 -> 25
String sql = "select * from my_table ORDER BY "+param1+" "+param2+" LIMIT "+param3+", "+param4;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println("Name = "+rs.getString("field1")+" Type = "+rs.getString("field2"));
}
} catch (SQLException e) {
e.printStackTrace();
}
Here, the print statement gives the output as desired. I want to use queryForList as it suits our data format requirements. How can I make sure that the order is maintained in queryForList?
You cannot pass the order by as parameters - ORDER BY ? ?. This will result in ORDER BY "firstSort", "secondSort"rather than ORDER BY firstSort, secondSort.

How to use ampersand in JDBC?

In oracle we using select * from table_name where column_name=&value in similar way how to use ampersand in JDBC?
stmt = conn.createStatement();
String sql;
sql="select emp_name from employees"+" where emp_no=?";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
String emp_name=rs.getString("emp_name");
System.out.println(emp_name);
}
i wrote the above code but it is not working(showing error)
Did you read the article I provided the link to?
You use the question mark ? to point out places in your query where you want to specify a parameter, and you have to use PreparedStatement. I can't test it, but it should be something like this:
// some code to obtain the Connection object
PreparedStatement stmt = null;
String yourQuery = " SELECT emp_name FROM employees WHERE emp_no = ? ";
try {
stmt = conn.prepareStatement(yourQuery);
stmt.setLong(1, 252);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
String emp_name = rs.getString("emp_name");
System.out.println(emp_name);
}
} finally {
// close the stmt etc.
}
I'd suggest using a PreparedStatement - from memory it's something like
Connection conn = getConnection();
PreparedStatement pstmnt = conn.prepareStatement("Select * from employees where emp_no =?");
pstmnt.setLong(1,emp_no);
ResultSet rs = pstmnt.executeQuery();
but the link that #Przemyslaw Kruglej high light above will almost certainly have a good example ( I haven;t read it though ... )

Why a select query is running slower in Oracle than sql server

I am reading data from Oracle database by using ODP.Net with the follwing code
OracleConnection con = new OracleConnection(connectionString);
OracleCommand cmd = new OracleCommand( SELECT ID,RECORD(XMLType) FROM tbl_Name, con);
con.Open();
OracleDataReader _dataReader = cmd.ExecuteReader();
while (_dataReader.Read())
{
string rowId = _dataReader[0].ToString();
string xmlString = _dataReader[1].ToString();
adding this data into Queue for further processing
}
It working fine but in a minute it's reading only 10000 record. If I use SqlServer database it's reading 500000 record in minute having table with same schema.
Please help me if I am missing something to read data faster using ODP.NET
Thank you.
**
ANSWER:
**
I have tried with GetClobVal() and GetString Val() functions, now it is working fine.
select t.RECID, t.XMLRECORD.GetClobVal() from tableName t"
select x.RECID,x.XMLRECORD.getStringVal() from tableName x"
If we use these queries with oracle command it will run fast, but not as fast as sql server query.

could not execute native bulk manipulation query

I am trying to implement a "if exists, update, otherwise, insert" data access method in NHibernate. My database is Oracle 10g.
I am getting this "could not execute native bulk manipulation query" error when try to run this code, if I run the insert or update individualy, it works just fine.
Thanks!
string sql = #"DECLARE
CntOfRow Number(10,0);
BEGIN
SELECT count(*)
INTO CntOfRow
FROM Table1
WHERE
QueID=:QueID
IF CntOfRow=0 THEN
INSERT INTO Table1 ...;
ELSE
UPDATE Table1 ... ;
END IF;
END;";
INHibernateSession session = NHibernateSessionManager.Instance.Session;
try
{
session.BeginTransaction();
ISQLQuery query = session.GetISession().CreateSQLQuery(sql.Replace(System.Environment.NewLine, " "));
query.SetParameter("QueID", queID);
query.ExecuteUpdate();
session.CommitTransaction();
}
catch (Exception ex)
{
session.RollbackTransaction();
throw;
}
I don't know why you get that error, but you could try this simpler PL/SQL block instead:
BEGIN
INSERT INTO Table1 ...;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
UPDATE Table1 ... ;
END;";
You seem to be missing an ; after the SELECT
This link might also be of interest to you.
As about inserting/updating, see MERGE statement. It works like this:
MERGE INTO t1 dest
USING (SELECT 1 pk, 11 i FROM dual) src
ON (dest.pk = src.pk)
WHEN NOT MATCHED THEN INSERT (dest.pk, dest.i) VALUES (src.pk, src.i)
WHEN MATCHED THEN UPDATE SET dest.i = src.i;
Also see this topic
Go to an Oracle client like Toad or SQL Editor and try to execute the procedure with the same parameters that you send through Hibernate.
In my case, Oracle was throwing an error like:
11:50:57 ORA-01403: no data found
The cause was a select inside of procedure/function. Then improve the procedure/function to catch these exceptions.

Resources