I have the following linq to sql query:
DateTime linqdate = (from de in dvlist
where de.DataValue == value
select de.DateTime);
I want to get the date value form database in a datetime variable but I got the following error:
cannot implicitly convert type
'System.Collections.Generic.IEnumerable'
to 'System.DateTime'
any ideas where the problem is? thanks in advance
A Linq query returns an IEnumerable<T> that you can iterate or you can convert it to another type of object (using some extension methods)
In order to get what you want you should do something like this :
var dateTime=(from de in dvlist
where de.DataValue == value
select de.DateTime).FirstOrDefault();
this way you are returning the first element of your enumerable object, or the default value for that type (T, in this case DateTime) if there is no match in the query.
Related
I got values stored in my database column field as value1,value2,value3,value4, so a simple_array column.
So i'm using Doctrine to make a search using this:
$searchQuery = $this->getDoctrine()
->getRepository('AppBundle:Ads')
->createQueryBuilder('p')
->andWhere("p.vals <= :value2")
->setParameter('value2', $request->query->get('value2'));
->orderBy("p.creationtime", 'DESC');
So expecting value2 is in the 2nd position of a simple array like value1,value2,value3, how can i ask QueryBuilder to select the second value in the string?
I think this query try to get all the values in p.vals, results are not right, shound select just one.
How can I select eg. the 2nd value in p.vals?
I believe you cannot access nth item of an array column using pure Mysql since the data is serialized, in order to do it I'd create a simple function
public function getItemFromArray(array $array, $index)
{
return isset($array[$index]) ? $array[$index] : null;
}
And if you want to find item with condition use
array_filter()
I have a postgres database to which I read/write using JOOQ. One of my DB tables has a column of type JSON. When I try to insert data into this column using the query below, I get the error
Exception in thread "main" org.jooq.exception.DataAccessException: SQL [update "public"."asset_state" set "sites_as_json" = ?]; ERROR: column "sites_as_json" is of type json but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
Below is the code for inserting data into the column
SiteObj s1 = new SiteObj();
s1.setId("1");
s1.setName("Site1");
s1.setGeofenceType("Customer Site");
SiteObj s2 = new SiteObj();
s2.setId("2");
s2.setName("Site2");
s2.setGeofenceType("Customer Site");
List<SiteObj> sitesList = Arrays.asList(s1, s2);
int result = this.dsl.update(as).set(as.SITES_AS_JSON, LambdaUtil.convertJsonToStr(sitesList)).execute();
The call LambdaUtil.convertJsonToStr(sitesList) outputs a string that looks like this...
[{"id":"1","name":"Site1","geofenceType":"Customer Site"},{"id":"2","name":"Site2","geofenceType":"Customer Site"}]
What do I need to do to be able to insert into the JSON column?
Current jOOQ versions
jOOQ natively supports JSON and JSONB data types. You shouldn't need to have to do anything custom.
Historic answer
For jOOQ to correctly bind your JSON string to the JDBC driver, you will need to implement a data type binding as documented here:
https://www.jooq.org/doc/latest/manual/code-generation/custom-data-type-bindings
The important bit is the fact that your generated SQL needs to produce an explicit type cast, for example:
#Override
public void sql(BindingSQLContext<JsonElement> ctx) throws SQLException {
// Depending on how you generate your SQL, you may need to explicitly distinguish
// between jOOQ generating bind variables or inlined literals.
if (ctx.render().paramType() == ParamType.INLINED)
ctx.render().visit(DSL.inline(ctx.convert(converter()).value())).sql("::json");
else
ctx.render().sql("?::json");
}
I have a MySQL date stored in DATETIME format. So I would like to know how to use date() in my Doctrine QueryBuilder's where clause. For example, 2013-02-01 12:51:17 is the date in MySQL. But I need to retrieve only the date. This is what I have tried:
$qb = $this->getEntityManager()->createQueryBuilder()
->select('t.balance','a.id','t.date')
->from('TestMainBundle:Transaction','t')
->groupBy('a.id')
->orderBy('a.id')
->where("t.date in date('t.date') ");
return $qb->getQuery()->getResult();
I received the following error:
QueryException: [Syntax Error]: Error: Expected Doctrine\ORM\Query\Lexer::T_OPEN_PARENTHESIS, got 'date'
Hi You can use SUBSTRING to fix your probleme
->where('SUBSTRING(t.date, 1, 10) IN (:param)')
->setParameter('param', array('2017-04-06'))
As it is pointed out in the comments, you cannot use mysql-specific date() or date_format() functions in Doctrine.
But for the particular case of searching a certain date in the datetime field, you can treat a date like a string, and thus use LIKE operator
->Where('t.date LIKE :date')
->setParameter(':date', "$date%")
As of
But I need to retreive only the date
you just format the returned value using format("Y-m-d") method. i.e.
echo $row->getDate()->format("Y-m-d");
You don't need the "date" in your where clause.
Juste remove it like this :
->where('t.date in (:yourwanteddate)')
->setParameter('yourwanteddate', '2013-02-01 12:51:17');
I'm having problems translating the following CASE Statement on SELECT to SQLAlchemy ORM. I keep getting the error : "Ambiguous literal: False. Use the 'text()' function to indicate a SQL expression literal, or 'literal()' to indicate a bound value."
The Case statement checks a variable, and then either returns a column on the database or selects a literal. The literal is set prior to running the sql statement.
DECLARE #str_cntry_cd varchar(3)
SELECT COUNTRY_CD,
CASE WHEN #str_cntry_cd IS NOT NULL THEN RESOLUTION_ID
ELSE 10
END AS RESOLUTION_ID
FROM COUNTRY
The SQLAlchemy code looks as follows:
country_tbl = getattr(main_db.Base.classes, "COUNTRY")
c_res = case([(country_code != None, country_tbl.RESOLUTION_ID),],
else_ = literal(10)).label("resolution_id")
programs_sa = main_db.session.query(country_tbl.COUNTRY_CD.label("country_cd"),
c_res).all()
The table is as follows:
CREATE TABLE dbo.COUNTRY
(
COUNTRY_CD varchar(4) NOT NULL,
RESOLUTION_ID int NOT NULL
)
SQLAlchemy .9.9
Windows 7
SQL Server 2008 R2
Python 2.7
country_code != None is causing the problem.
That evaluates to python's True/False, which SQLAlchemy doesn't know how to convert to SQL's true/false as it is ambiguous. So you would need to either add the literal true/false for the SQL you are using, by using SQLAlchemy's text or literal functions. But a better way would be to use the true or false functions.
http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.true
http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.false
So you would replace the buggy section of the code with:
db.false() if country is None else db.true()
Hope this helps.
I am tring to compare a date from a asp calendar control to a date in the table.... here's what i have... it doesn't like the == ?
var query = from details in db.TD_TravelCalendar_Details
where details.StartDate == calStartDate.SelectedDate
&& details.EndDate == calEndDate.SelectedDate
select details;
In order for your query to work both details.StartDate and calStartDate.SelectedDate must be typed as System.DateTime.
What error are you receiving? Most likely one of these properties is a string and will need to be parsed into a DateTime instance for comparison.
What is the Type of details.StartDate and details.EndDate? Is it String? Maybe that's the problem. If the database type is String you should Parse the Date String into a DateTime and compare it with the calendar's selected date then.