Got Null result from Oracle even though the real result are decimal value - oracle

I am new to Oracle in Visual Studio,
I used Oracle.ManagedDataAccess as my reference,
The case is whenever I tried to retrieve decimal value from arithmetic in Oracle query, Its always return null
e.g
SELECT 26/3 FROM DUAL < ---- This code return null in my visual studio but has a value in TOAD.
Did I do it wrong ?
Here is my code to retrieve the value
List<object[]> result = new List<object[]>();
OracleDataReader data;
string constr = ConfigurationManager.ConnectionStrings["OraConnection"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
string query = QueryString;
using (OracleCommand cmd = new OracleCommand(query))
{
cmd.Connection = con;
con.Open();
data = cmd.ExecuteReader();
try
{
if (data.HasRows)
{
while (data.Read())
{
object[] itemData = new object[data.FieldCount];
//Dictionary<string, string> itemData = new Dictionary<string, string>();
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
if (typeof(string) == type)
{
itemData[i] = data.GetString(i);
}
if (typeof(DateTime) == type)
{
itemData[i] = data.GetDateTime(i);
}
if (typeof(int) == type)
{
itemData[i] = data.GetInt32(i);
}
if (typeof(decimal) == type)
{
itemData[i] = data.GetDecimal(i);
}
if (typeof(bool) == type)
{
itemData[i] = data.GetBoolean(i);
}
if (typeof(TimeSpan) == type)
{
itemData[i] = data.GetTimeSpan(i);
}
if (typeof(Single) == type)
{
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
}
}
result.Add(itemData);
}
}
else
{
Console.WriteLine("Rows not found.");
}
}
finally
{
data.Close();
}
con.Close();
}
}
return result;
UPDATED : It got null just for division which has decimal value. Addition, Substraction, multiplication has no issue

It seems your data type doesn't match any of your if expressions. As there is no default branch, itemData[i] remains null. I suggest something like the following to find the gap:
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
switch(type)
{
case typeof(string):
itemData[i] = data.GetString(i);
break;
case typeof(DateTime):
itemData[i] = data.GetDateTime(i);
break;
case typeof(int):
itemData[i] = data.GetInt32(i);
break;
case typeof(decimal):
itemData[i] = data.GetDecimal(i);
break;
case typeof(bool):
itemData[i] = data.GetBoolean(i);
break;
case typeof(TimeSpan):
itemData[i] = data.GetTimeSpan(i);
break;
case typeof(Single):
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
break;
default:
MessageBox.Show("Unknown type " + type.Name);
break;
}
}

So, I got an advice to edit the oracle query
From (e.g.)
SELECT 26/7 FROM DUAL
TO
SELECT TO_CHAR(26/7) FROM DUAL
And yes it works
But still, I don't know why

Related

Spring GCP - Datastore performance: Batch processing, iteration through all entity list is very slow

Following code is work really slow, almost 30 second to process 400 entities:
int page = 0;
org.springframework.data.domain.Page<MyEntity> slice = null;
while (true) {
if (slice == null) {
slice = repo.findAll(PageRequest.of(page, 400, Sort.by("date")));
} else {
slice = repo.findAll(slice.nextPageable());
}
if (!slice.hasNext()) {
break;
}
slice.getContent().forEach(v -> v.setApp(SApplication.NAME_XXX));
repo.saveAll(slice.getContent());
LOGGER.info("processed: " + page);
page++;
}
I use following instead, 4-6 sec per 400 entities (gcp lib to work with datastore)
Datastore service = DatastoreOptions.getDefaultInstance().getService();
StructuredQuery.Builder<?> query = Query.newEntityQueryBuilder();
int limit = 400;
query.setKind("ENTITY_KIND").setLimit(limit);
int count = 0;
Cursor cursor = null;
while (true) {
if (cursor != null) {
query.setStartCursor(cursor);
}
QueryResults<?> queryResult = service.run(query.build());
List<Entity> entityList = new ArrayList<>();
while (queryResult.hasNext()) {
Entity loadEntity = (Entity) queryResult.next();
Entity.Builder newEntity = Entity.newBuilder(loadEntity).set("app", SApplication.NAME_XXX.name());
entityList.add(newEntity.build());
}
service.put(entityList.toArray(new Entity[0]));
count += entityList.size();
if (entityList.size() == limit) {
cursor = queryResult.getCursorAfter();
} else {
break;
}
LOGGER.info("Processed: {}", count);
}
Why I can't use spring to do that batch processing?
Full discussion here: https://github.com/spring-cloud/spring-cloud-gcp/issues/1824
First:
you need to use correct lib version: at least 1.2.0.M2
Second:
you need to implement new method in repository interface:
#Query("select * from your_kind")
Slice<TestEntity> findAllSlice(Pageable pageable);
Final code looks like:
LOGGER.info("start");
int page = 0;
Slice<TestEntity> slice = null;
while (true) {
if (slice == null) {
slice = repo.findAllSlice(DatastorePageable.of(page, 400, Sort.by("date")));
} else {
slice = repo.findAllSlice(slice.nextPageable());
}
if (!slice.hasNext()) {
break;
}
slice.getContent().forEach(v -> v.setApp("xx"));
repo.saveAll(slice.getContent());
LOGGER.info("processed: " + page);
page++;
}
LOGGER.info("end");

Problem two query db2 sqlserver is not print output

This is the correct example, which does not work:
If the LANGUAGE column is the same as the LANGUAGE COLUMN and the NLS_CLASS_NAME column is the same as the KEYWORD COLUMN
Given that they are true, if you noticed the language string I turned it into lowercase and I cut the string so that it becomes "en", since it was first ENG
You must print the language list, keyword is translation
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
//Traduzione in Db2 a SqlServer
public void getTraduzione() throws Exception {
List<DizioPt> listDizio = new ArrayList<DizioPt>();
List<ClassHdrNls> listHdr = new ArrayList<ClassHdrNls>();
String className = "";
String language = "";
String nlsClassName = "";
String lingua = "";
String keyword = "";
String traduzione = "";
Database database = new Database();
// Db2
Connection dbConnectionDb2 = null;
Statement statementDb2 = null;
// SqlServer
Connection dbConnectionSqlServer = null;
Statement statementSqlServer = null;
// Query Db2
String queryDb2 = "select * from THERA.CLASS_HDR_NLS WHERE
THERA.CLASS_HDR_NLS.LANGUAGE='en'";
// Query SqlServer
String querySqlServer = "select * from DIZIOPT WHERE
DIZIOPT.LINGUA='ENG'";
try {
// Connessione --> SqlServer
dbConnectionSqlServer = database.getConnectionSqlServer();
statementSqlServer = dbConnectionSqlServer.createStatement();
// Connessione -->Db2
dbConnectionDb2 = database.getConnectionDb2();
statementDb2 = dbConnectionDb2.createStatement();
// Risultato SqlServer
ResultSet rsSqlServer = statementSqlServer.executeQuery(querySqlServer);
// Risultato Db2
ResultSet rsDb2 = statementDb2.executeQuery(queryDb2);
while (rsSqlServer.next() && rsDb2.next()) {
ClassHdrNls classHdrNls = new ClassHdrNls();
className = rsDb2.getString("CLASS_NAME");
classHdrNls.setClassName(className);
language = rsDb2.getString("LANGUAGE");
classHdrNls.setLanguage(language);
nlsClassName = rsDb2.getString("NLS_CLASS_NAME");
classHdrNls.setNlsClassName(nlsClassName);
listHdr.add(classHdrNls);
DizioPt diziopt = new DizioPt();
lingua = rsSqlServer.getString("LINGUA");
diziopt.setLingua(lingua);
keyword = rsSqlServer.getString("KEYWORD");
diziopt.setKeyword(keyword);
traduzione = rsSqlServer.getString("TRADUZIONE");
diziopt.setTraduzione(traduzione);
listDizio.add(diziopt);
for (int i = 0; i < listHdr.size(); i++) {
for (int j = 0; j < listDizio.size(); j++) {
if (listHdr.get(i).getNlsClassName().equalsIgnoreCase(listDizio.get(j).getKeyword())
&& listHdr.get(i).getLanguage()
.equalsIgnoreCase(listDizio.get(j).getLingua().toLowerCase().substring(0, 2))) {
System.out.println("Class name: " + listHdr.get(i).getClassName());
System.out.println("Lingua: " + listHdr.get(i).getLanguage());
System.out.println("Testo: " + listHdr.get(i).getNlsClassName());
System.out.println("Traduzione: " + listDizio.get(j).getTraduzione());
}
}
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statementDb2 != null && statementSqlServer != null) {
statementDb2.close();
statementSqlServer.close();
}
if (dbConnectionDb2 != null && dbConnectionSqlServer != null) {
dbConnectionDb2.close();
dbConnectionSqlServer.close();
}
}
}

ArrayIndex is not supported in LINQ to Entities

// update information from this reponse to database
public bool UpdatePassengerInformation(GetResponse response)
{
try
{
using (MyEntities context = new MyEntities())
{
var masterID = (from Id in context.BookMaster where Id.BookingId == response.BookingId select Id.MasterId).First();
if (masterID != null)
{
for (int i = 0; i < response.Book.Length; i++)
{
var passenger_info = from passenger in context.BookPassenger
where passenger.BookID == masterID &&
assenger.FirstName == response.Book[i].FirstName && passenger.LastName == response.Book[i].LastName select passenger;
// in below loop i got exception "The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities."
foreach (BookPassenger book_passenger in passenger_info)
{
book_passenger.TicketId = response.Book[i].TicketId;
book_passenger.TicketNumber = response.Book[i].TicketNumber;
}
}
context.SaveChanges();
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
}
So don't use it in query, just assign a new variable and use this one.
for (int i = 0; i < response.Book.Length; i++)
{
var responseBook = response.Book[i];
var passenger_info = from passenger in context.BookPassenger
where passenger.BookID == masterID &&
assenger.FirstName == responseBook.FirstName && passenger.LastName == responseBook.LastName select passenger;
foreach (BookPassenger book_passenger in passenger_info)
{
book_passenger.TicketId = responseBook.TicketId;
book_passenger.TicketNumber = responseBook.TicketNumber;
}
}

Update a single column to EF 6.0 using LINQ lambda ? MVC4

I want to save the data when i edit something in my data-table on enter .
On enter control goes to method in controller where actual update performs .
My code till this point:
public string UpdateData(int id, string value, int? rowId, int? columnPosition, int? columnId, string columnName)
{
var Leadsinfo = ser_obj1.Lead_List();
if (columnPosition == 0 && Leadsinfo.Any(c => c.Contact_Name.ToLower().Equals(value.ToLower())))
return "Lead with a name '" + value + "' already exists";
var Lead = Leadsinfo.FirstOrDefault(c => c.Lead_Id == id);
if (Lead == null)
{
return "Lead with an id = " + id + " does not exists";
}
switch (columnPosition)
{
case 0:
Lead.Contact_Name = value;
iWise_NeoEntities ooo = new iWise_NeoEntities();
break;
case 1:
Lead.Contact_Address = value;
break;
case 2:
Lead.Lead_Source = value;
break;
case 3:
Lead.Domain = value;
break;
default:
break;
}
return value;
}
In the above code i mentioned i need to write logic where it should save to DB upon any column editing . using lambda linq is easy i guess , But i dont know even how to start ?
Do i need to write save under each case?
You can create update method in database:
public void UpdateLead(Lead model)
{
var entity = db.Set<Lead>().Find(model.Id);
db.Entry<Lead>(entity).CurrentValues.SetValues(model);
db.SaveChanges();
}
And use it where you need:
switch (columnPosition)
{
case 0: Lead.Contact_Name = value; break;
case 1: Lead.Contact_Address = value; break;
case 2: Lead.Lead_Source = value; break;
case 3: Lead.Domain = value; break;
default: break;
}
iWise_NeoEntities ooo = new iWise_NeoEntities();
ooo.UpdateLead(Lead);

Dynamically Set Column Name In LINQ Query

Im trying to write a method which will allow me to search different DataTables, over different columns.
So far i have the following:
string selectedValue;
string searchColumn;
string targetColumn;
var results = (from a in dt.AsEnumerable()
where a.Field<string>(searchColumn) == selectedValue
select new
{
targetColumn = a.Field<string>(targetColumn)
}).Distinct();
Which kind of gets the job done, but I'm left with the column name as targetColumn rather than the actual column name I want.
Is there any way to resolve this?
Thanks in advance
CM
I make a LINQ to Datatables
public List<DataRow> Where(this DataTable dt, Func<DataRow, bool> pred)
{
List<DataRow> res = new List<DataRow>();
try {
if (dt != null && dt.Rows.Count > 0) {
for (i = 0; i <= dt.Rows.Count - 1; i++) {
if (pred(dt(i))) {
res.Add(dt(i));
}
}
}
} catch (Exception ex) {
PromptMsg(ex);
}
return res;
}
Usage :
var RowsList = dt.Where(f => f("SomeField").toString() == "SomeValue" ||
f("OtherField") > 5);

Resources