mysql parameterized query in ASP.NET - mysql

i am working on parameterized queries but i am not getting proper query in result
here is my code
public MySqlCommand Get_Login(string clinetID, string loginID, string password, string branchID)
{
MySqlCommand objCommand = new MySqlCommand(this.Query);
objCommand.Parameters.AddWithValue("#ClientID", clinetID);
objCommand.Parameters.AddWithValue("#LoginID", loginID);
objCommand.Parameters.AddWithValue("#Password", password);
objCommand.Parameters.AddWithValue("#BranchID", branchID);
objCommand.CommandType = CommandType.Text;
return objCommand;
}
and when debugging this is what i am getting in "objCommand"
Select u.groupid,p.PersonId, p.designationid,concat(p.salutation,p.FName,'
',p.MName,' ',p.LName) as PersonName,tb.Type
BrType,p.OrgId,p.subdepartmentid,ifnull(crossdept,'N') as
crossdept,p.departmentid,u.defaultpage,p.orgid,ifnull(p.crosslab,'N') as crosslab,
(select indoor_services from dc_Tp_organization where orgid='#ClientID') as
indoor_services,(select name from dc_Tp_organization where orgid='#ClientID') as
orgname,
(select default_route from dc_Tp_organization where orgid='#ClientID') as
default_route,p.BranchID BranchID,tb.Name BRName from dc_tp_personnel p left outer
join
dc_tu_userright u on u.personid=p.personid left outer join dc_tp_branch tb on
tb.BranchID=p.BranchID Where p.Active='Y' and p.LoginId = '#LoginID' and p.Pasword
='#Password' and p.BranchID='#BranchID'
i am not getting values in parameters
Here is the Query
objdbhims.Query = "Select u.groupid,p.PersonId,
p.designationid,concat(p.salutation,p.FName,' ',p.MName,' ',p.LName) as
PersonName,tb.Type BrType,p.OrgId,p.subdepartmentid,ifnull(crossdept,'N') as
crossdept,p.departmentid,u.defaultpage,p.orgid,ifnull(p.crosslab,'N') as crosslab,
(select indoor_services from dc_Tp_organization where orgid=#ClientID) as
indoor_services,(select name from dc_Tp_organization where orgid=#ClientID) as
orgname,(select default_route from dc_Tp_organization where orgid=#ClientID) as
default_route,p.BranchID BranchID,tb.Name BRName from dc_tp_personnel p left outer
join dc_tu_userright u on u.personid=p.personid left outer join dc_tp_branch tb on
tb.BranchID=p.BranchID Where p.Active='Y' and p.LoginId = #LoginID and p.Pasword
=#Password and p.BranchID=#BranchID";

Secret Squirrel was correct on using the "?" for parameterized variables. MySQL uses "#" for inline sql variables for queries and thus expecting them to be declared such as from a script or part of an inline (select subquery) declaration.
You need to change BOTH instances of the parameters... both in the query, and as the command.Parameters.Add... instances.
Also, I noticed, and not sure if its it or not, but in your WHERE clause you have "pasword" (only one 's') vs password (two 's') Don't know if intentional or not.
One LAST thing that MAY help. Since some of the parameters match the column names, I would suggest changing the parameters SLIGHTLY by just adding something like "x" to FORCE differentiation between the column name and the actual parameters...
where... p.LoginID = ?xLoginID ...
and in the command parameters
objCommand.Parameters.AddWithValue("?xLoginID", loginID);

The problem is because the parameters were wrap with single quotes converting them into string literals.
To make it work, remove the single quotes around them. eg.
Where p.Active = 'Y'
and p.LoginId = #LoginID
and p.Pasword = #Password
and p.BranchID = #BranchID

Related

Use select filed result on LEFTJOIN string

I'm trying to use id_program result from the availability table inside a string in LEFTJOIN, is it possible?
I tried using this {post.id_program} but its not working.
SELECT *
FROM availability post
LEFT JOIN postmeta meta5 ON meta5.post_id = post.id_post
AND meta5.meta_key = 'items_iti_port_{post.id_program}_nights_iti_port'
WHERE post.id_post=462
EDIT:
http://sqlfiddle.com/#!9/aeb4a7/3
I see two ways..
Using CONCAT():
meta5.meta_key = CONCAT('items_iti_port_', post.id_program, '_nights_iti_port')
With REPLACE():
meta5.meta_key = REPLACE('items_iti_port_%_nights_iti_port', '%', post.id_program)

Linq to entity adding Where() clause breaks query

Using Microsoft SQL Entity Framework I've got a query where sometimes I have a filter condition and sometimes I don't, so I tried to do what I've shown below. If the condition is not null then instead of doing the query as expected it queries everything from the Org_Hierarchy table, and then queries everything from the Workers table, and then dies as that takes too long:
void SomeMethod(Func<PRT, bool> whereClause) {
IQueryable<PRT> query;
if (whereClause != null) {
query = PRT.Where(whereClause).AsQueryable();
} else {
query = PRT.AsQueryable();
}
var data = from prt in query
// LEFT OUTER JOIN Worker a ON prt.assigned_to = a.WWID
join a_join in Worker on prt.assigned_to equals a_join.WWID into a_grp
from a in a_grp.DefaultIfEmpty()
// LEFT OUTER JOIN Worker c ON prt.closed_by = c.WWID
join c_join in Worker on prt.closed_by equals c_join.WWID into c_grp
from c in c_grp.DefaultIfEmpty()
// LEFT OUTER JOIN Worker r ON prt.requestor = r.WWID
join r_join in Worker on prt.requestor equals r_join.WWID into r_grp
from r in r_grp.DefaultIfEmpty()
// LEFT OUTER JOIN Org_Hierarchy o ON prt.org3 = o.OrganizationHierarchyUnitCd AND o.OrganizationHierarchyUnitTreeLevelNbr = 3 AND o.Active = true
join o in Org_Hierarchy on prt.org3 equals o.OrganizationHierarchyUnitCd
select new PrtInput {
If I change the query and put something direct in there, just for testing, like where prt.id == Guid.NewGuid() right above the last line shown then the query returns in one second. What's the trick to be able to dynamically add a where clause to the query?
The above code is from LinqPAD which is why the normal "context" stuff is all missing.
I'm not sure , but i think you should use something like this :
Expression<Func<PRT ,bool>> whereClause
Insted of:
Func<PRT ,bool> whereClause
When you using Func<> , first fetch data from db to memory then filter data in memory ,but if you use Epression<> filter send to sql and return result.
Also for the better performnce you can use AsNoTracking() like this:
if (whereClause != null) {
query = PRT.Where(whereClause).AsQueryable().AsNoTracking();
} else {
query = PRT.AsQueryable().AsNoTracking();
}
When you only want run query on yout database without any Insert ,update or delete on result , it better use AsNoTracking.
I hope this answers your question.

Why did this query change work?

I ended up scrapping the part of the WHERE clause that was giving me issues, but initially I got this query working by doing something that didn't make sense to me at all, and was hoping someone could shine some light on what is going on here. The entire query and function are below, but I'm not sure all of that is necessary
So this query was previously working and this WHERE clause is still being used successfully in another query. Now multiple functions are used in this line of the where clause, however if I just use the portion starting with ModifiedStartDate the query works fine. So it seems like the issue is with ModifiedDate. The portion of the WHERE clause that was giving us issues was:
and ModifiedDate(r.EXPIRATION_DATE, ModifiedStartDate(r.COMMENCEMENT_DATE,
PaySched_MaxFreq(r.RE_CONTRACT_KEY))) > #1/1/2019#
The query was failing with the error "Data type mismatch in criteria expression". So just doing some testing I ended up adding the following portion to the WHERE clause:
and r.RE_CONTRACT_KEY NOT IN (1)
And then the query worked?!?! I really don't get how adding this line magically resolved a data type mismatch error. There is no RE_CONTRACT_KEY = 1 so it's not bad data or something.
I did some testing and took the ModifiedDate function and put that into the select clause and it worked fine. I also added another field to the SELECT clause using the DATEADD function to make sure the function result was still being treated as a date, and it was. Query is below and the function is below that.
SELECT DISTINCT ....
FROM ((((((PAYMENT_LINE_ITEM AS pli
INNER JOIN PAYMENT_SCHEDULE AS tps ON pli.PAYMENT_SCHEDULE_KEY =
ps.PAYMENT_SCHEDULE_KEY)
INNER JOIN RECONTRACT AS r ON pli.RE_CONTRACT_KEY = r.RE_CONTRACT_KEY)
INNER JOIN Conversion_ProductCategory AS cpc ON cpc.Value = pli.PAYMENT_TYPE)
INNER JOIN ManualEntry AS me ON me.LeaseID = r.RE_CONTRACT_ID)
LEFT JOIN Mapping_CostCenter AS mcc ON mcc.CostCenter = me.CostCenter)
INNER JOIN PIW_Exclusions AS pe ON pe.RE_CONTRACT_ID = r.RE_CONTRACT_ID)
LEFT JOIN FacilityCode_Address_xRef AS fca ON fca.[Facility Code] =
mcc.placecode & "-" & mcc.placecodedescription
WHERE pli.PAYMENT_TYPE in ("rent","storage","parking")
and ModifiedDate(r.EXPIRATION_DATE,
ModifiedStartDate(r.COMMENCEMENT_DATE,
PaySched_MaxFreq(r.RE_CONTRACT_KEY))) > #1/1/19#
and PE.Reason = "rent extension"
and r.RE_CONTRACT_KEY NOT IN (1) 'New line added that made query work
And the function:
Public Function ModifiedDate(DateToModify As Date, DateToCompare As Date) As
Date
Select Case DateToModify
Case #2/28/2000#, #2/28/2004#, #2/28/2008#, #2/28/2012#, #2/28/2016#,
#2/28/2020#, #2/28/2024#, #2/28/2028#, #2/28/2032#, #2/28/2036#, #2/28/2040#,
#2/28/2044#, #2/28/2048#
DateToModify = DateAdd("d", 1, DateToModify)
End Select
If DatePart("d", DateAdd("d", 1, DateToModify)) = DatePart("d",
DateToCompare) Then
ModifiedDate = DateAdd("d", 1, DateToModify)
Else
ModifiedDate = DateToModify
End If
End Function
If you're curious the final working WHERE clause is:
WHERE pli.PAYMENT_TYPE in ("rent","storage","parking")
and r.EXPIRATION_DATE > #1/1/19#
and PE.Reason = "rent extension"

unknown class: Fixnum Rails MySQL query - inserting variable breaks my search

I had a query which was working just fine:
#schedule = Schedule.find(params[:id])
#schedule_tasks = ScheduleTask.select("s.*, t.*, t.*, d.*, st.*").from("schedule_tasks st").
joins("left join schedules s ON s.id = st.schedule_id").
joins("left join tasks t ON t.id = st.task_id").
joins("right join days d ON d.id = st.day_id").
order("d.number, t.name").
group_by{|d| d.number}
I had to refine my search to only schedule_tasks with a specific schedule_id, so I edited the second line to:
joins("left join schedules s ON s.id = st.schedule_id AND s.id = ?", #schedule.id).
This has cause the following error:
unknown class: Fixnum
The error goes away if I take out the group_by - but I need that, and I have tried hard coding in the number instead of #schedule.id and that does not work either, a google search does not reveal a lot of details on this error.
For anyone coming here from Google, I used plain string interpolation to fix this issue. This method is vulnerable to SQL Injection, so make sure you type check your variables before using them.
In this case I would do
#schedule_id = #schedule.id
.
.
.
joins("left join schedules s ON s.id = st.schedule_id AND s.id = #{#schedule_id}")
Rather than following learning_to_swim's answer, which as noted is at risk of SQL injection, couldn't you cast your #schedule_id to a string?
#tasks = ScheduleTask.joins("left join [...] s.id = ?", #schedule.id.to_s)

Comparing dates in iif() in SQL Server

I am trying to use the following query in SQL Server
SELECT [AL].[Subscriptions].Id,
[AL].[Subscriptions].name,
[AL].[Subscriptions].description,
[AL].[Subscriptions].price,
[AL].[Subscriptions].iconFileName,
IIf(a.expiryDate > Now(), 'TRUE', 'FALSE') AS isSubsByUser
FROM [AL].[Subscriptions]
LEFT JOIN (SELECT *
FROM [AL].[UserSubscriptions]
WHERE userId = 13259) AS a
ON Subscriptions.Id = a.itemid;
but always get the error
Error in list of function arguments: '>' not recognized.
Unable to parse query text.
How do I resolve it?
Like Martin Smith said you need to use a case statement. Also it looks like you are only using a couple of fields in the derived table therefor I would suggest not using *. I put a example below.
SELECT [AL].[Subscriptions].Id,
[AL].[Subscriptions].name,
[AL].[Subscriptions].description,
[AL].[Subscriptions].price,
[AL].[Subscriptions].iconFileName,
case when a.expiryDate > GetDate() then 'TRUE' else 'FALSE' end AS isSubsByUser
FROM [AL].[Subscriptions]
LEFT JOIN (SELECT expiryDate, itemid
FROM [AL].[UserSubscriptions]
WHERE userId = 13259) AS a
ON Subscriptions.Id = a.itemid;