Named query with optional parameter not working in mysql - mysql

I have a named query below for optional parameter which is flightNumber, departureAirport and arrivalAirport. But this query is not working when I don't give any value for these parameter.
#Query("from CapacityMonitor
where carrierCode = :carrierCode and
(:flightNumber IS NULL OR flightNumber = :flightNumber) and
(:departureAirport IS NULL OR departureAirport = :departureAirport) and
(:arrivalAirport IS NULL OR arrivalAirport = :arrivalAirport)
I can change a query but i have to use with #Query annotation only

So you want to keep your query the way it is and make it work with or without parameters. Well, you can't do that. If the query is expecting parameters, then you have to set them.
The best approach would be to leave the query the same way it is and set the parameters to NULL so that :param IS NULL returns TRUE in those cases and return all results. That way you will fake a match.
Anyway, the parameter has to be set always.

I would suggest using a Criteria Query to build a statement with custom WHERE clause.
Based on your example, it could look like this (depending on your data types):
public List<CapacityMonitor> getFlights(String carrierCode, String flightNumber, String departureAirport, String arrivalAirport) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<CapacityMonitor> query = builder.createQuery(CapacityMonitor.class);
Root<CapacityMonitor> root = query.from(CapacityMonitor.class);
query.select(root);
// Carrier code is mandatory
query.where(builder.equals(root.get("carrierCode"), carrierCode));
// Other properties are optional
if (null != flightNumber && flightNumber.length() > 0) {
query.where(builder.equals(root.get("flightNumber"), flightNumber));
}
// Use LIKE expression to match partially
if (null != departureAirport && departureAirport.length() > 0) {
query.where(builder.like(root.get("departureAirport"), "%" + departureAirport + "%"));
}
if (null != arrivalAirport && arrivalAirport.length() > 0) {
query.where(builder.like(root.get("arrivalAirport"), "%" + arrivalAirport + "%"));
}
return em.createQuery(query).getResultList();
}

Related

Trying to check the value of a cell and compare it to another value to see if it matches(Google Script)

I am trying to creating a booking system, and as of now I am going to allow my user to insert their name and then check if there is a value. But whenever I try to simply accomplish this by using if( m == 'string) it thinks that all of the empty spaces are strings which results in everything saying booked.
Function checkifBooked(name)
{
var string ='BOOKED';
var string2 ='FREE';
if(typeof name == 'string')
{
return string;
}
else{
return string2;
}
}
When you get the value of an empty cell you get an empty string '', which is still a string. Thus, your if always evaluates to True.
In javascript, an empty string evaluates to false, so you can test the string directly.
try:
if(name)
Or if you prefer to be more explicit, you could check the type of name, then check it's length.
if(typeof(name) == 'string' && name.length > 0)

PDO query does not return data when inserting date as variable

Im trying to get a hold of OOP and PDO. Did some tutorials. In the tutorial i got the query method (so thats not mine...)
but im having troubles with a pdo query
I want to select orders from the database matching a date..... de date comes from a datepicker and returns 2012-12-16 for example therefor
$dateInputQuery = date("Y-m-d", strtotime(Input::get('datepick')));
$data = $order->getAllOrders('order', 'WHERE DATE(orderdate) = DATE({$dateInputQuery})', false, false);
the strange thing is that when i replace the WHERE clause to WHERE DATE(orderdate) = \'2013-12-16\' it returns all the data but when inserting my date like above it does not....
in the db class the method looks like this
public function getAll($table, $where = NULL, $orderSort = NULL, $limit = NULL) {
$this->query("SELECT * FROM {$table} {$where} {$orderSort} {$limit}")->error();
return $this;
}
and query method in db class
public function query($sql, $params = array()) {
//reset error
$this->_error = false;
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if (count($params)) {
foreach ($params as $param) {
$this->_query->bindValue($x,$param);
$x++;
}
}
if ($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
why is this ?
Your immediate problem is caused the fact that $dateInputQuery is unquoted. Date is a string literal and should be quoted. And even though you can easily add quotes around it you really shouldn't do this. See next point.
order is a reserved word in MySQL, therefore the table name should be put in backticks
$data = $order->getAllOrders('`order`', "WHERE DATE(orderdate) = DATE('$dateInputQuery')", false, false);
^ ^ ^ ^
You're not leveraging parameter binding in query() function. Instead on top of it you're using query string interpolation leaving your code vulnerable to sql injections and diminishing the usage of prepared statements. When you use parameter binding you no longer need to quote parameter values.
Your sql query is not index-friendly. You shouldn't apply any functions (in your case DATE()) to the column you're searching on (orderdate). Instead you can rewrite your condition to apply necessary transformations/calculations to the arguments which are constants.
You should avoid using SELECT *. Read Which is faster/best? SELECT * or SELECT column1, colum2, column3, etc and Why is using '*' to build a view bad?
That being said your query should look something like
$sql = "SELECT order_id, orderdate, ...
FROM `order`
WHERE orderdate >= ?
AND orderdate < ? + INTERVAL 1 DAY";
And you should execute it
$this->query($sql, array($dateInputQuery, $dateInputQuery));
Instead of passing whole clauses (e.g. WHERE) you should pass values

linq mysql : select multiple column and send the to view

I have selected multiple columns from my table, but I don't know how to pass it to my view.
var result = (from f in db.firmware
where f.firmware_release_type_text != ""
|| f.firmware_release_type_text != null
|| f.firmware_release_number_int != 0
select new{
f.firmware_release_type_text,
f.firmware_release_number_int
}).Distinct();
The result is f__anonymous2. I want to some how use it in my view. all the forums have just answered how to choose multiple columns, but nobody mentions how to pass them. I think I'm missing something obvious.
I want to be able to use this fields, or even merge them as one string.
I have tried Cast and so many other options which did not work.
When I try to force casting it sting, I get :
Unable to cast the type 'Anonymous type' to type 'System.String'
Thanks
UPDATE:
At the end I went with:
var result = (from f in db.firmware
where (f.firmware_release_type_text != "")
&& (f.firmware_release_type_text != null)
&& (f.firmware_release_number_int != 0)
select new{
f.firmware_release_type_text,
f.firmware_release_number_int
}
).Distinct();
List<string> result2 = new List<string>();
foreach (var item in result)
{
result2.Add(item.firmware_release_type_text
+ "-" + item.firmware_release_number_int);
}
If you want to return your data as a string you have to say how it should be formatted. You could for example change this:
select new
{
f.firmware_release_type_text , f.firmware_release_number_int
}
To this:
select f.firmware_release_type_text + " v" + (int)f.firmware_release_number_int
You have two options to create a model first, second format the data on the server side.

How do I return values from a function with LINQ

Below is the code sample I cant figure the return type, this function belongs to a class clsExhibitorlist. I want to bind this to my gridview.
public ??? GetExhibitorList()
{
using (DataClasses1DataContext context = new DataClasses1DataContext())
{
var Exhibitors = from c in context.Companies
join b in context.Booths on c.CoID equals b.CoID
join bc in context.BoothCategories
on b.BoothID equals bc.BoothID
join sp in context.SubProductCategories
on bc.SubProdCatID equals sp.SubProdCatID
join p in context.ProductCategories on
sp.ProdCatID equals p.ProdCatID
orderby c.CoID
select new clsExhibitorList { c.CoID, c.CompanyName, b.FPCoName,p.ProdCatID,sp.SubProdCatID};
if (Keyword != "")
{
Exhibitors = Exhibitors.Where(c => c.CompanyName.Contains(Keyword));
}
if (ProdCatID != "")
{
Exhibitors = Exhibitors.Where(c => c.ProdCatID.Equals(ProdCatID.Split(',')));
}
if (SubProdCatID != "")
{
Exhibitors = Exhibitors.Where(c => c.SubProdCatID.Equals(SubProdCatID.Split(',')));
}
return Exhibitors;
}
}
Ah I dont see anything in the code to actually invoke the query. So the method returns an expression tree representing the query.
If you add something like .ToList() on the return statement the query will be forced to be evaulated and the return type will then be
List < clsExhibitorList >
You can find an explaination of what is going on here (Delayed Evaluation) in this blog post:
http://devlicio.us/blogs/derik_whittaker/archive/2008/04/07/linq-and-delayed-execution.aspx
Note that i dont beleive you can bind against an expression tree to you will have add the .ToList or .ToArray or .ToDictionary or similar, best place to add it would be on the return statement so that as much processing as possible will occur in the database

Why are null strings in my database not returned with returnFormat = JSON

{
MESSAGE = LoginWelcomeBackMessage;
SUCCESS = 1;
USER = {
AcceptAllFriendRequests = 0;
CreateDate = "June, 07 2010 00:00:00";
DayOfBirth = "April, 24 1974 00:00:00";
UserName = "Erik Madsen";
};
}
My CFC defines all the columns in my database table, but when a column is NULL, the field isn't returned as a property in the JSON? The example above should have PersonalInfo = ""; Is there a way to force it to return an empty string?
Simply leaving the property out is probably closer to null than an empty string in most circumstances. if you want an empty string you should return an empty string. how a null value is treated depends on your serializer.
In javascript, the official implementation handles it quite fine:
var a = { b: null };
console.log( JSON.stringify(a) ); // logs '{"b":null}'
An empty string in a database column is not the same as a NULL in a column.
Have a look at this article: http://www.bennadel.com/blog/1654-Learning-ColdFusion-9-IsNull-And-Working-With-NULL-Values.htm
Typically, you may want to wrap these at the database (in a view or a computed column) with ISNULL(col, '') or COALESCE(col, '') or handle these after extraction from the database as the article discusses. Or don't even allow NULLs in the database, require empty strings instead.