Getting results from sql statement in dart, odbc - html

i got i hope simple question but i can't find answers in internet or i just still dont understand how to do that.
I want to execute sql statement and than get result and insert in my table, but i can't find proper function for that like there are in jdcb.
i found some examples but still dunno what to do.
code:
static void RegisterTable()
{
var hStmt = new SqlHandle();
sqlAllocHandle(SQL_HANDLE_STMT, MyConnect, hStmt);
sqlPrepare(hStmt, "SELECT R.[ID],U.[NAME],C.[CAR_NAME],R.[DESTINATION],R.[START_DATE],R.[END_DATE],R.[STATUS] FROM CAR_BOOKING.Registr_car R JOIN CAR_BOOKING.CARS C ON R.Car_id = C.id JOIN CAR_BOOKING.Users_table U ON U.id = R.user_id WHERE R.STATUS !=2;", SQL_NTS);
// Bind result set columns.
var id = new SqlIntBuffer();
var name = new SqlStringBuffer(70);
var carname = new SqlStringBuffer(70);
var destination = new SqlStringBuffer(70);
var startdate = new SqlDateBuffer(70);
var enddate = new SqlDateBuffer();
var status = new SqlIntBuffer(70);
sqlBindCol(hStmt, 1, id.ctype(), id.address(), id.length(),null);
sqlBindCol(hStmt, 2, name.ctype(), name.address(), name.length(),null);
sqlBindCol(hStmt, 3, carname.ctype(), carname.address(), carname.length(),null);
sqlBindCol(hStmt, 4, destination.ctype(), destination.address(), destination.length(),null);
sqlBindCol(hStmt, 5, startdate.ctype(), startdate.address(), startdate.length(),null);
sqlBindCol(hStmt, 6, enddate.ctype(), enddate.address(), enddate.length(),null);
sqlBindCol(hStmt, 6, status.ctype(), status.address(), status.length(),null);
sqlExecute(hStmt);
List<Object> result = sqlFetch(hStmt);
sqlFreeHandle(SQL_HANDLE_STMT, hStmt);
}
How to get this result to any container like List or print into rows ?

Related

Making custom sort in google script faster

I'm trying to organize a database by a rank in a certain order that I want. Normally, sort would work, but I want a couple of things to happen:
1. raw data so that filters can work for other data (i.e. by name, team, etc)
2. I don't want to always sort by rank
Ranks in order:
Captain, Officer, Chef, Crew, Recruit, Lost, Brig
Right now I'm forcing a filtered sort first alphabetically only when the rank filter is sorted, then when that is done, it sorts the list according to the above sort. The problem that I'm having is that it takes some time to execute the script. I'm thinking that this can be done much more efficiently, but I'm way rusty when it comes to this stuff. Here's my code below:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var members = ss.getSheetByName("Members");
var temp = ss.getSheetByName("sortRank");
var ranks = ["Captain", "Officer", "Chef", "Crew", "Recruit", "Lost", "Brig"];
var rankData = members.getRange(1,5,members.getLastRow(),1);
var search = null;
var query = null;
var x = null;
if(order != null) {
ranks = ranks.reverse();
}
for (var i=0; i < 7; i++) {
search = rankData.createTextFinder(ranks[i]);
x = search.findAll().length;
if(x != 0) {
query = search.findNext().getRow();
members.getRange(query,1,x,37).copyTo(temp.getRange(temp.getLastRow()+1,1));
}
}
}
Sort members by rank:
Assumes rank is in column 5 of members.
var members = ss.getSheetByName("Members");
var rankData = members.getRange(1,5,members.getLastRow(),1).getValues();
var ranks = ["Captain", "Officer", "Chef", "Crew", "Recruit", "Lost", "Brig"];
var rVal={};
ranks.forEach(function(e,i){rVal[e]=i+1;});
members.getDataRange().setValues(members.getDataRange().getValues().sort(function(a,b){return rVal[a[4]]-rVal[b[4]];}));

I don't know how to convert sql query to criteriabuilder in hibernate?

I need an total budget value. I can getting the answer from sql query but the problem is how to convert sql query to criteriaBuilder in hibernate.Here below the sql query:
SELECT SUM(ab.daily_budget) as todayBudgetTar FROM api_budget ab INNER JOIN api_ad_groups ad on ad.ad_group_id= ab.adgroup_id INNER JOIN api_campaigns c on c.campaign_id =ad.campaign_id INNER JOIN api_user_account ac on ac.user_id=ad.user_id WHERE ad.user_id = 234 AND ad.status=0 AND c.status=1 GROUP by "todayBudgetTar"
If someone knows plz help me.
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
Root<ApiBudget> budget = query.from(ApiBudget.class);
Root<ApiAdGroups> adGroups = query.from(ApiAdGroups.class);
Root<ApiCampaigns> campaigns = query.from(ApiCampaigns.class);
Root<ApiUserAccount> userAccount = query.from(ApiUserAccount.class);
//this one is on your entity field name
query.select(criteriaBuilder.sum(budget.get("dailyBudget"));
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(
qb.equal(adGroups.get("adGroupId"), budget.get("adGroupId")));
predicates.add(
qb.equal(campaigns.get("campaignId "), adGroups.get("campaignId")));
predicates.add(
qb.equal(userAccount.get("userId"), adGroups.get("userId")));
predicates.add(
qb.equal(adGroups.get("userId"), 234));
predicates.add(
qb.equal(adGroups.get("status"), 0));
predicates.add(
qb.equal(campaigns.get("status"), 1));
query.where(predicates.toArray(new Predicate[]{}));
query.groupBy(budget.get("dailyBudget"));
TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
List<Object[]> resultList = typedQuery.getResultList();
Hi, i think this should work
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Object> query = builder.createQuery(Object.class);
Root<Budget> budget = query.from(Budget.class);
Join adsetJoin = budget.join("adsetId");
Join campaignJoin = adsetJoin.join("campaign");
query.multiselect(builder.sum(budget.get("dailyBudget")));
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(builder.equal(adsetJoin.get("status"), 0));
predicates.add(builder.equal(adsetJoin.get("userId"), userId));
predicates.add(builder.equal(campaignJoin.get("campaignStatus"), CAMPAIGNSTATUS.RUNNING));
if ((dashboardRequest.getStartDate() != null) && (dashboardRequest.getEndDate() != null)) {
Date fromDate = new Date(dashboardRequest.getStartDate());
Date toDate = new Date(dashboardRequest.getEndDate());
predicates.add(builder.between(adsetJoin.get("createdDate"), fromDate, toDate));
}
if (!predicates.isEmpty()) {
Predicate[] pr = new Predicate[predicates.size()];
pr = predicates.toArray(pr);
query.where(pr);
}
query.groupBy(budget.get("dailyBudget"));
List<Object> resultList = session.createQuery(query).getResultList();
List<Long> resultList2=resultList.stream().map(v ->((Number)v).longValue()).collect(Collectors.toList());
return resultList2;

getting my SQL query to be displayed in LINQ form

I am very new to writing LINQ statements, and I am struggling to write this simple SQL in LINQ form.
SELECT Type, COUNT(*) as [Total Submissions]
FROM Submission
GROUP BY Type
this is my attempt:
var query = from s in db.Submission
group s.Type
Type = s.Type
Total = s.Type.Count()
This is what my output should be:
Type Count of Type
Book 10
Chapter 15
Journal 8
Conference 4
Using LINQ syntax:
var result = from x in db.Submission
group x by x.Type into grp
select new {
Type = grp.Key,
Count = grp.Count()
};
Using lambda syntax:
var result = db.Submission
.GroupBy(x => x.Type)
.Select(x => new {
Type = x.Key,
Count = x.Count()
});

How to write Linq-To-SQL statment which is equal to my following TSQL?

TSQL:-
Update table1
Set Name = 'John',
Address = null
where
ID = 1
LINQ-TO-SQL
var tab = db.Table1.Single(s => s.ID == 3);
tab.Name = DateTime.Now;
tab.Address = null;
db.SubmitChanges();
There isn't a single LINQ to SQL statement for updates. You have to retrieve the object, modify it, then save the changes (code assumes a single row since you have a specific Id):
var entity = context.Table1.Single(t => t.Id == 1);
entity.Name = "John";
entity.Address = "Toronto";
context.SubmitChanges();
using (var dataContext = new MyEntities())
{
var contact = Contacts.Single (c => c.ContactID == 1);
contact.FirstName = 'John';
contact.Address= 'Toronto';
dataContext.SaveChanges();
}

Help to build LINQ query

I have SQL database as follows
alt text http://img97.imageshack.us/img97/5774/dbimage.jpg
Now I want to filter the restaurant_detail table for the parameters:
1. cuisine 2. area
Can you help me to build LINQ query?
I presume you have a model generated either with LINQ to SQL or Entity Framework. Also, I'm assuming foreign key relationships have been set.
var details = db
.Cuisines
.Where(c => c.Cuisine=="something")
.SelectMany(c => c.RestaurantCuisines)
.Select(rc => rc.Restaurant.RestaurantDetails)
.Where(rd => rd.Area=="something")
;
Done with the linq query using following lines of code :
c = from q in dc.restaurant_cuisines
where q.cuisine.cuisine1.Contains(cuisine)
&& q.restaurant.price.ToString().Length == price.Length
select new NearBy { NearById = q.restaurant.id, NearByLongitude = (double)q.restaurant.longitude, NearByLatitude = (double)q.restaurant.latitude };
}
int[] ids = new int[c.Count()];
var lon = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.longtitude;
var lat = from q1 in dc.area_maps where q1.area.ToLower() == area.ToLower() select q1.latitude;
foreach(NearBy n in c)
{
result = calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), n.NearByLatitude, n.NearByLongitude);
ids[i++] = n.NearById;
}
var r = from q in dc.restaurant_details
where 1 == 1 &&
(ids).Contains(q.restaurant_id)
select new Restaurant
{
Restora_id = q.restaurant_id.ToString(),
Name = q.restaurant.name,
Foodtype = q.restaurant.foodtype.foodtype1,
Avg_rating = q.restaurant.avg_rating.ToString(),
Featured = q.restaurant.featured.ToString(),
CuisineList = getCuisine(q.restaurant_id),
Restora_type = q.type,
Distance = Math.Round(calcDistNew((double)lat.FirstOrDefault(), (double)lon.FirstOrDefault(), (double)q.restaurant.latitude, (double)q.restaurant.longitude), 2),
Newarrival = q.restaurant.newarrival.ToString(),
CountRecord = ids.Length.ToString()
};
var d = r.AsEnumerable().OrderBy(t => t.Distance);
var g = d.Take(recordSize + 10).Skip(recordSize);
return g.ToList();
Please note that above displayed code generated with some changes from the initial requirements.