I try to display the Total sum() from a sqlStmt but all i got is [object, object], any idea how?
Thanks
private function displayAmountHeading():void {
sqlStmt = new SQLStatement();
sqlStmt.sqlConnection = sqlConn;
sqlStmt.text = "SELECT SUM(Amount) FROM MainTable";
sqlStmt.execute();
var result:Array = sqlStmt.getResult().data;
if (result != null) trace(result);
}
//return [object, object]
You're attempting to trace an array. If you want to see the first value in that array, try
SELECT SUM(Amount) as sum FROM MainTable
trace(result[0].sum);
The object,object is the string representation of the object, without a toString() method. Use trace(ObjectUtil.toString(result)); If your new to the flex sqlStatement you should also read this and this
for more information about the return type of the sqlStatement and how to access properties of the result object, when using aggregate functions such as SUM, where u should use aliases, such as SUM(Amount) as sumAmount to later access the property, like resultObject["sumAmount"] or resultObject.sumAmount
Related
I'm using sqlite3.exe to execute queries against my DB, using the following code.
public static string QueryDB(string query)
{
string output = System.String.Empty;
string error = System.String.Empty;
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "C:\\sqlite\\sqlite3.exe";
startInfo.Arguments = "test.db " + query;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
try
{
using(System.Diagnostics.Process sqlite3 = System.Diagnostics.Process.Start(startInfo))
{
output = sqlite3.StandardOutput.ReadToEnd();
error = sqlite3.StandardError.ReadToEnd();
sqlite3.WaitForExit();
}
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.ToString());
return null;
}
return output;
}
I'm inserting data into a table, and I'd like it to return the id of the inserted data. Is there a way to get SQLite to do this?
For example, my query might look like this "INSERT INTO mytable (some_values) VALUES ('some value');". After this query is run, I'd like output to contain the rowid of the inserted data. Is there any way to do this (a command line switch, etc.)?
A possible workaround, is to run two commands against the DB. First insert the data, then get the last inserted row id. In which case, the query would look like this "\"INSERT INTO mytable (some_values) VALUES ('some value'); SELECT last_insert_rowid();\""
You should not use max(id) or similar function in DB.
In this specific case it can work, under the condition that you use ONE connection and ONE thread to write data to DB.
In case of multiple connections you can get wrong answer.
From version SQLite 3.35.0 it supports returning close in the insert statement (SQLite Returning Close)
create table test (
id integer not null primary key autoincrement,
val text
);
insert into table test(val) values (val) returning id;
Would you consider this:
select max(id) from your_table_name;
or embedded function last_insert_rowid()?
Hello I have to write in linq the sql query below:
Declare #OrgID int
Declare #OrgFinalID int
Set #OrgID = 91702 ---91703, 91702, 83279
select #OrgFinalID =
case
when ParentOrganisationId is null then ItemID
else ParentOrganisationId
end
from Organisations
where ItemID = #OrgID
I tried to write this but I am not on the right way, sorry but I am new with LINQ:
var OrgID=91207;
var OrgFinalID = from o in context.Organisations
where o.ItemID == OrgID
select new
{
o.ParentOrganisationId == null ? o.ItemID : o.ParentOrganisationId,
}
I have to put, with the LINQ expression, the value inside the variable OrgFinalID.
Looks like you are expecting this to be just a single number? Than you can call .Single() on your query, that basically returns the value itself:
var OrgFinalID = (from o in context.Organisations
where o.ItemID == OrgID
select new
{
ID = o.ParentOrganisationId == null ? o.ItemID : Convert.ToInt32(o.ParentOrganisationId),
}).Single().ID;
Also note call to Convert.ToInt32 which is supported by Linq to SQL and should help you avoid type casting problem.
Other options:
SingleOrDefault - if there could be single result, or no result at all (returns null in this case)
First - if you expect one or more results from the query
FirstOrDefault - similar to SingleOrDefault , returns null if no results came from the query
Im trying to return an IQueryable based on my model.
But I need to join to the same lookup table twice. Then return the query variable to the gridview.
public IQueryable<Benchmark> GetBenchMarks([QueryString("hydrant")] string hydrant,
[QueryString("revdate")] string revdate, [QueryString("street")] string street,
[QueryString("quadrant")] string quadrant, [QueryString("desc")] string desc) {
IQueryable<Benchmark> query = from p in _db.Benchmarks
join s in _db.Streets on p.Street1Number equals s.Id
join s2 in _db.Streets on p.Street2Number equals s2.Id
select new {
Street1Name = s.StreetName,
p.OrderNumber,
p.HydrantNumber,
Street2Name = s2.StreetName,
p.RevisionDate,
p.Quadrant,
p.Description,
p.Street1Number
};
}
So there is a red squiggle line on the 2nd join to s2. And the following error.
Error 5 Cannot implicitly convert type
'System.Linq.IQueryable<AnonymousType#1>' to
'System.Linq.IQueryable<Benchmarks.Model.Benchmark>'. An explicit
conversion exists (are you missing a
cast?) C:\Projects\Benchmarks\Benchmarks\Benchmarks_Home.aspx.cs 63 25 Benchmarks
Since you end your query with select new {...}, you are creating an anonymous object for each result. Instead, use select p, and each result will be a Benchmark.
However, it looks like returning a Benchmark is not what you want. In this case, you would want to change query to be of type IQueryable or IQueryable<dynamic> (and probably change the return type of the GetBenchMarks function as well, unless it does return IQueryable<Benchmark>!).
A second (potentially better) alternative would be to create a class to represent this anonymous type, and use that.
The result of your query is IEnumerable of anonymous objects, thus it cannot be converted to Benchmark.
If you want to set some additional properties (Street1Name - that are evidently not mapped on DB) from joined relations you can do:
IQueryable<Benchmark> query = from p in _db.Benchmarks
join s in _db.Streets on p.Street1Number equals s.Id
join s2 in _db.Streets on p.Street2Number equals s2.Id
select new {
....
};
var ex = query.ToList();
var result = new List<Benchmark>();
foreach(bn in ex){
result.Add(new Benchmark{ OrderNumber = bn.OrderNumber .... });
}
// return result.AsQueryable();
// but now it losts the point to return it as queryable, because the query was already executed so I would simply reurn that list
return result;
Another option is to make new class representing the object from the query and return it from the method like:
... select new LoadedBenchmark { Street1Name = s.StreetName ....}
I have researched on the net and most result are converting from sql to linq and seldom have linq to sql.
this is the code which I want to convert to SQL :
using (CommerceEntities db = new CommerceEntities())
{
try
{
var query = (from ProductOrders in db.OrderDetails
join SelectedProducts in db.Products on ProductOrders.ProductID
equals SelectedProducts.ProductID
group ProductOrders by new
{
ProductId = SelectedProducts.ProductID,
ModelName = SelectedProducts.ModelName
} into grp
select new
{
ModelName = grp.Key.ModelName,
ProductId = grp.Key.ProductId,
Quantity = grp.Sum(o => o.Quantity)
} into orderdgrp where orderdgrp.Quantity > 0
orderby orderdgrp.Quantity descending select orderdgrp).Take(5);
RepeaterItemsList.DataSource = query;
RepeaterItemsList.DataBind();
}
catch (Exception exp)
{
throw new Exception("ERROR: Unable to Load Popular Items - " +
exp.Message.ToString(), exp);
}
}
You can attempt to run the LINQ statement in LinqPad. For examples on how to use LinqPad, check the answer here.
It has a tab to show the generated SQL statement.
Here's an article on logging in LINQ to SQL. It lets you specify a TextWriter to which to send the query.
Basically, you can write something like this:
db.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true };
... where db is your data context.
In SQL you'd write something like this (although the produced code will look a lot different, since it is auto-generated):
SELECT TOP 5 Products.ModelName, Products.ProductID, SUM(OrderDetails.Quantity) qty
FROM OrderDetails
INNER JOIN Products ON OrderDetails.ProductID = Products.ProductID
GROUP BY Products.ProductID, Products.ModelName
HAVING qty > 0
ORDER BY qty DESC
I am using entity framework with the following linq query
IQueryable<Order_Details> query = (from ord in ctx1.Order_Details
where ord.OrderID == 1
select ord).ToArray();
gv1.DataSource = query;
gv1.DataBind();
I get a result ok, return a row with orderId of 1
When I use the following,
var query = (from ord in ctx1.Order_Details
where ord.OrderID == 1
select ord).First() as IQueryable<Order_Details>;
gv1.DataSource = query;
gv1.DataBind();
I don't recive any results in the gridview
First() returns the Order_Detail record itself, not a collection/array, and therefore is not IQueryable; so using as IQueryable<Order_Details> will return null because it can't be cast. Casting to IQueryable<> can only work for an enumerable of some sort.
If you have to use First, bind to the gridview like this:
var query = (from ord in ctx1.Order_Details
where ord.OrderID == 1
select ord).First();
gv1.DataSource = new[] { query };
gv1.DataBind();
You're trying to cast a single Order_Details object to IQueryable<Order_Details>
Since that's not a valid cast, null is being returned, and your grid is not showing any results.
Your GridView is expecting an IEnumerable, so your original code was correct. Why did you try to change it?