ResultSet coming as empty after executing query - sql

I have a query
SELECT instance_guid FROM service_instances WHERE service_template_guid='E578F99360A86E4EE043C28DE50A1D84' AND service_family_name='TEST'
Directly executing this returns me
4FEFDE7671A760A8DC8FC63CFBFC8316
F2F9DF641D8E2CACC03175A7A628D51D
Now I am trying same code from JDBC.
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = executionContext.getConnection();
if (conn != null) {
ps = (PreparedStatement)conn.prepareStatement(query);
if (params == null) params = new Object[0];
for (int i=0;i<params.length;i++) {
if (params[i] instanceof Integer) {
ps.setInt(i+1, ((Integer)params[i]).intValue());
} else if (params[i] instanceof java.util.Date) {
((PreparedStatement)ps).setDATE(i+1, new oracle.sql.DATE((new java.sql.Timestamp(((Date)params[i]).getTime()))));
//ps.setObject(i+1, new oracle.sql.DATE(new Time(((Date)params[i]).getTime())));
} else {
if (params[i] == null) params[i] = "";
ps.setString(i+1, params[i].toString());
}
}
rs = ps.executeQuery();
I see params[0] =E578F99360A86E4EE043C28DE50A1D84 and params[1]=TEST
But the resultSet is empty and not getting the result.I debugged but not much help?
Can you please let me know Am i trying right?
In java its defined as below
final static private String INSTANCE_GUID_BY_TEMPLATE_GUID =
"SELECT instance_guid FROM service_instances WHERE service_template_guid=? AND service_family_name=? "
SERVICE_FAMILY_NAME NOT NULL VARCHAR2(256)
SERVICE_TEMPLATE_GUID NOT NULL RAW(16 BYTE)

First and foremost this breaks every sql mapping pattern I have ever seen.
String sql = "SELECT instance_guid FROM service_instances WHERE service_template_guid=? AND service_family_name=?";
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = executionContext.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1,guid);
ps.setString(2,family);
rs = ps.executeQuery();
while(rs.next(){...}
...
}
You should not be dynamically figuring out the data types as they come in, unless you are trying to write some code to port from database X to database Y.
UPDATE
I see you are using RAW as a datatype, from this post:
As described in the Oracle JDBC Developer's guide and reference 11g,
when using a RAW column, you can treat it as a BINARY or VARBINARY
JDBC type, which means you can use the JDBC standard methods
getBytes() and setBytes() which returns or accepts a byte[]. The other
options is to use the Oracle driver specific extensions getRAW() and
setRAW() which return or accept a oracle.sql.RAW. Using these two will
require you to unwrap and/or cast to the specific Oracle
implementation class.
Further from a code readability standpoint, your solution makes it painful for a new developer to take over. Far too often I see people making sql be "dynamic" when in reality 99% of the time you don't need this level of dynamic query building. It sounds good in most people's heads but it just causes pain and suffering in the SDLC.

Related

How to set large string as param without getting ORA-01460: unimplemented or unreasonable conversion error?

In spring-boot using namedParameterJdbcTemplate (Oracle db version 12 and odbc8 driver 12.2)
I am getting the following error while executing a SELECT query bound with a parameter larger than 4000 character whereas update queries working fine.
ORA-01460: unimplemented or unreasonable conversion requested
The unit test I am trying to execute;
#Test
public void testSqlSelectQueryLargeStringParameter() {
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("param", theLargeStr);
// #formatter:off
String sql =
"SELECT NULL id, NULL text FROM DUAL WHERE 'X' != :param ";
// #formatter:on
namedParameterJdbcTemplate.queryForRowSet(sql, params);
}
Is there any way to set this large param via MapSqlParameterSource?
I am #ahmet-orhan 's colleague, we've found a solution.
Thanks #kfinity for your suggestion, It is working for insert and update but we are still getting this error when we set clob or blob as "paremeter" in select statements.
If using a driver that supports JDBC4.0, the right solution is create a DefaultLobHandler and set streamAsLob or createTemporaryLob to true.
MapSqlParameterSource params = new MapSqlParameterSource();
String myString = "";
for (int i = 0; i < MAX_CLOB_BLOB_SIZE_IN_SELECT; i++) {
myString = myString + "1";
}
DefaultLobHandler lobHandler = new DefaultLobHandler();
lobHandler.setStreamAsLob(true);
params.addValue("param", new SqlLobValue(myString, lobHandler), Types.CLOB);
// #formatter:off
String sql =
"SELECT 1 id FROM DUAL WHERE :param IS NOT NULL ";
// #formatter:on
Integer id = namedParameterJdbcTemplate.queryForObject(sql, params, Integer.class);
We prefer streamAsLob but to be honest we have no idea which one is better.
This comment points out that ORA-01460 in JDBC queries is the same as "ORA-01704: string literal too long". (You can't have string literals longer than 4000 characters.) Maybe try this solution?
params.addValue("param", theLargeStr, Types.CLOB);
Although also != won't work for clob comparison, so you'll also need to change your query to
SELECT NULL id, NULL text FROM DUAL WHERE dbms_lob.compare('X',:param) != 0

Apache Calcite | HSQLDB - Table Not Found Exception

I am trying to learn Apache Calcite by following the RelBuilderExample with the storage layer being HSQLDB.
Unfortunately, I keep getting "Table Not Found exception" when i call builder.scan(tableName) API of Apache Calcite. When I query the data in HSQL directly using ResultSet rs = statement.executeQuery("SELECT * from file"); then i am able to retrieve the data. Here is the relevant code:
//I create an instance of RelBuilder using the Config defined below
RelBuilder builder = RelBuilder.create(config().build());
//This line throws me exception: org.apache.calcite.runtime.CalciteException: Table 'file' not found
builder = builder.scan("file");
/**
Building the configuration backed by HSQLDB
*/
public static Frameworks.ConfigBuilder config() throws Exception{
//Getting the ConnectionSpec for the in memory HSQLDB
//FileHSQLDB.URI = "jdbc:hsqldb:mem:intel"
//FileHSQLDB.USER = "user"
//FileHSQLDB.PASSWORD = "password"
final ConnectionSpec cs = new ConnectionSpec(FileHSQLDB.URI, FileHSQLDB.USER, FileHSQLDB.PASSWORD, "org.hsqldb.jdbcDriver", "intel");
//cs.url = "jdbc:hsqldb:mem:intel"
//cs.driver = "org.hsqldb.jdbcDriver"
//cs.username = "user"
//cs.password = "password"
DataSource dataSource = JdbcSchema.dataSource(cs.url, cs.driver, cs.username, cs.password);
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
//This returns me 3 results
ResultSet rs = statement.executeQuery("SELECT * from file");
while(rs.next()) {
String id = rs.getString("file_id");
System.out.println(id);
}
// Next I create the rootSchema
SchemaPlus rootSchema = Frameworks.createRootSchema(true);
//I suspect that there is some issue in the below line. I think I
//am not using Apache Calcite APIs properly, but not sure what I
//am doing wrong.
rootSchema.add("intel", JdbcSchema.create(rootSchema, "intel", dataSource, cs.catalog, cs.schema));
return Frameworks.newConfigBuilder().defaultSchema(rootSchema);
Can someone please help me what I may be doing wrong.
If your table is file (lowercase) then make sure you quote the table name in the query, i.e. "SELECT * from \"file\"".

Why do SQL joins fail in Oracle?

I just try simple joins with C# using oracle db. Should be no big deal. But it ALWAYS fails. It works in MS-Access. Where is the problem ? (OleDb or Odbc makes no difference here, I tried both)
Edit:
Might Oracle version be the problem ? (seems we are using 8.1.7.0.0 and 8.1.5.0.0 modules)
Code:
using System;
using System.Data.Odbc;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string n = Environment.NewLine + "--------------------------------" + Environment.NewLine + Environment.NewLine;
// connect
string connectionString = "dsn=TEST;uid=read;pwd=myPwd";
OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();
// select (key is actually text not numeral)
string query = "select * from INFOR.ZEITEN where (KEY = 0)";
query = "select a.KEY, b.GREG from INFOR.ZEITEN a inner join INFOR.ZEITEN b on (a.AUSWEIS = b.AUSWEIS) where (a.KEY like '1')";
try
{
query = query.Replace(Environment.NewLine, " ");
Console.WriteLine(n + query);
OdbcCommand command = new OdbcCommand(query, connection);
OdbcDataReader reader = command.ExecuteReader(); // throws exception
if (reader != null)
Console.WriteLine(n + "success, now read with reader!");
}
catch (Exception e)
{
Console.WriteLine(n + e.Message + n + e.StackTrace);
}
// wait
Console.ReadKey();
}
}
}
Output:
And the successful, simple select:
ANSI joins (ex. inner join) were first supported in 9i. You will need to use the old syntax:
select a.KEY, b.GREG
from INFOR.ZEITEN a,
INFOR.ZEITEN b
where (a.AUSWEIS = b.AUSWEIS)
and (a.KEY like '1')
Note that the like operator is equivalent to = in this case, but you probably know that
I think the KEY is numeric then you can't use LIKE. It is because the WHERE KEY = 0 works fine.
The word key is a reserved word. That means that it is a very poor choice for an identity. You need to escape it with a double quote. This might work:
query = "select a.\"KEY\", b.GREG
from INFOR.ZEITEN a inner join
INFOR.ZEITEN b
on (a.AUSWEIS = b.AUSWEIS)
where (a.\"KEY\" like '1')";
I am guessing the \" will work in this context, but there might be another method to insert this character.
What's the error? Could you edit your question and add the actual error the system's throwing at you?
Firstly, I would personally recommend using the ODP .NET (Oracle Data provider for .NET). You can download the latest version for Oracle 12c here. Or look it up for the version you need.
ODBC is a very old driver written in C and works using the native Windows RPC technique.
For full .NET support you're better off with ODP .NET.
Secondly, check if you have any constraints on the tables that's causing the sql to fail.

Write SQL queries using LINQ from linq object List

I have a linq object and I want to write the query using linq.
please help me.
INPUT:
var tags = (from row in tempChildData.AsEnumerable()
join tagOrder in tupleInfoDataset.Tables["TagHierarchy"].AsEnumerable() on row.Field<Int64>("TAGID") equals tagOrder.Field<Int64>("TAGID")
join tagName in tupleInfoDataset.Tables["SequenceChoiceList"].AsEnumerable() on tagOrder.Field<Int64>("PARENTTAGID") equals tagName.Field<Int64>("TAGID")
join facet in tupleInfoDataset.Tables["FacetType"].AsEnumerable() on tagName.Field<string>("Tag_Name") equals facet.Field<string>("Facetname")
join tagIdInfo in schDataTogetTagid.AsEnumerable() on row.Field<string>("refTagName").Contains(":") ? row.Field<string>("refTagName").Split(':').Last():row.Field<string>("refTagName") equals tagIdInfo.Field<string>("TAGNAME")
where ( childList.Contains(row.Field<Int64>("TAGID")) && facet.Field<string>("FacetType").ToLower().Equals("ctype"))
select new
{
Tagid = row.Field<Int64>("TAGID"),
TagIdToInsert=tagIdInfo.Field<Int64>("TAGID"),
MaxOccur = row.Field<string>("Maxoccurs"),
MinOccur =Convert.ToInt32(Convert.ToString(row.Field<string>("Minoccur"))),
ParentTagId=tagOrder.Field<Int64>("PARENTTAGID"),
Order=tagOrder.Field<Int64>("TAG_ORDER"),
ParentTagname = tagName.Field<string>("Tag_Name"),
FacetId=facet.Field<Int64>("FacetID")
}).ToList();
var parentTagID = (from tagIdInfo in tupleInfoDataset.Tables["Tuple"].AsEnumerable()
where tagIdInfo.Field<Int64>("TAGID").Equals(key.Key)
select tagIdInfo.Field<Int64>("ConceptID")).ToList();
long parentID =Convert.ToInt64(parentTagID[0]);
Now i want the query out of the above code as:
INSERT INTO TUPLE_MAP (TagId,ParentTagId,ParentTagname,MinOccur,MaxOccur,Order)
VALUES (TagIdToInsert,ParentTagId,ParentTagname,MinOccur,MaxOccur,Order)
Please help me I don't know how to write SQL queries using linq
Maybe something like this:
using(var db=new DataContext("YourConnectionStringHERE"))
{
db.TUPLE_MAP.InsertAllOnSubmit(tags.Select (t =>
new TUPLE_MAP()
{
TagId=t.TagIdToInsert,
ParentTagId=t.ParentTagId,
ParentTagname=t.ParentTagname,
MinOccur=t.MinOccur,
MaxOccur=t.MaxOccur,
Order=t.Order
}));
db.SubmitChanges();
}
Or if you want to use the parentID then something like this:
using(var db=new DataContext("YourConnectionStringHERE"))
{
db.TUPLE_MAP.InsertAllOnSubmit(tags.Select (t =>
new TUPLE_MAP()
{
TagId=t.TagIdToInsert,
ParentTagId=parentID,
ParentTagname=t.ParentTagname,
MinOccur=t.MinOccur,
MaxOccur=t.MaxOccur,
Order=t.Order
}));
db.SubmitChanges();
}
where db is your linq data context
Useful references:
How to: Insert Rows Into the Database (LINQ to SQL)
EDIT
So if you are using the Compact database 3.5 then many something like this:
using (var conn =new SqlCeConnection("Data Source = test.sdf; Password ='pass'"))
{
foreach (var tag in tags)
{
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = #"INSERT INTO TUPLE_MAP (TagId,ParentTagId,ParentTagname,MinOccur,MaxOccur,Order)
VALUES (#TagIdToInsert,#ParentTagId,#ParentTagname,#MinOccur,#MaxOccur,#Order)";
cmd.Parameters.AddWithValue("#TagIdToInsert", tag.TagIdToInsert);
cmd.Parameters.AddWithValue("#ParentTagId", tag.ParentTagId);
cmd.Parameters.AddWithValue("#ParentTagname", tag.ParentTagname);
cmd.Parameters.AddWithValue("#MinOccur", tag.MinOccur);
cmd.Parameters.AddWithValue("#MaxOccur", tag.MaxOccur);
cmd.Parameters.AddWithValue("#Order", tag.Order);
cmd.ExecuteNonQuery();
}
}
}
Useful references:
Why can't I insert a record into my SQL Compact 3.5 database?
SqlCeCommand.Parameters Property
SqlCeCommand Class
SqlParameterCollection.AddWithValue Method
Use linq Pad or sql profiler to see the generated SQL.
You can also use visual studio for that purpose. In the debug mode,hold cursor on the variable "tags", you will be able to see the SQL.
I am assuming you are using Linq to SQL, if you are doing so you would have entity called Tuple_map in you xxxDataContext. Then you would just have to create object of that entity something like this....
using (XXXDataContext context = new XXXDataContext())
{
Tuple_map obj = new Tuple_map();
//Populate obj properties like obj.tabid = from objects you got it from above query
context.Tuple_map.InsertOnSubmit(obj);
context.SubmitChanges();
}

Can I get the T-SQL query generated from a LinqDataSource?

I´m using the LinqDataSource to populate a grid. But now I need the SQL query that the LinqDataSource generates, to pass around throught methods (no, I can't modify the methods to not need a SQL query).
Is there a way to obtain the generated SQL query from a instantiated and configured LinqDataSource?
Hope this helps.
using the function below will return a SqlQueryText
you can rebuild the query from that object.
to get the sql text you can use use the .Text Property
to get the passed
parameters you can use the .Params property
public static SqlQueryText GetFullQueryInfo(DataContext dataContext, IQueryable query)
{
DbCommand dbCommand = dataContext.GetCommand(query);
var result = new SqlQueryText();
result.Text = dbCommand.CommandText;
int nParams = dbCommand.Parameters.Count;
result.Params = new ParameterText[nParams];
for (int j = 0; j < nParams; j++)
{
var param = new ParameterText();
DbParameter pInfo = dbCommand.Parameters[j];
param.Name = pInfo.ParameterName;
param.SqlType = pInfo.DbType.ToString();
object paramValue = pInfo.Value;
if (paramValue == null)
{
param.Value = null;
}
else
{
param.Value = pInfo.Value.ToString();
}
result.Params[j] = param;
}
return result;
}
here is an example
var results = db.Medias.Where(somepredicatehere);
ClassThatHasThisMethod.GetFullQueryInfo(yourdatacontexthere, results);
EDIT:
Sorry forgot to include the SqlQueryText data structures
public struct SqlQueryText
{
public ParameterText[] Params;
public string Text;
}
public struct ParameterText
{
public string Name;
public string SqlType;
public string Value;
}
You can run SQL Profiler while running your application and that should give it to you.
Take a look at LinqPad for debugging and to understand how it works. But if you want it at run-time, I think you're out of luck.
The Sql will only be generated by the Linq to Sql infrastructure at runtime.
I think there are some tools to see generated Sql in the debugger, but if you don't plan to use linq to generate your Sql dynamicaly, shouldn't you probably look for a simple Sql designer ?
I Found a Linq To Sql Debug visualizer on Scottgu's blog.