How to insert date and Query date in SQLite table - sqlite

I am not familiar with SQLite on handling date.
The problem:
Can I insert date this way or insert any date using DateTime to create.
Order_Date = DateTime.Today
How to :
a) How to use a select or query a recordset base or Order_Date ?
b) How to select or query a recordset base on Date Range ? from this date to this date.
Thanks
Class Order
{
[PrimaryKey, AutoIncrement]
public int SId { get; set; }
public int CustId { get; set; }
public string No { get; set; }
public string Customer { get; set; }
public DateTime Order_Date { get; set; }
}
using (var db = new SQLite.SQLiteConnection(DBPath))
{
var newOrder = new Order()
{
CustId = g_intCustId,
Customer = txtBlkCustomer.Text.Trim(),
Order_Date = DateTime.Today
};
db.Insert(newOrder);
----- Update :
1) I wanted to know what is the proper way to insert date into a field of dateTime DataType in table as Above? using Date from DateTime.Today, DateTime.Now
2) what fields need to add in SQLite table when enter Date with
a) normal Date format ( dd/mm/yyyy)
b) format like : Date with HHMMSS
3) How to query or select Date for (2a) and (2b)?
Thanks

Can I insert date this way or insert any date using DateTime to create.
Order_Date = DateTime.Today
Yes, DateTime.Today while insertion will work. SQLite internally stores DateTime objects as string.
How to use a select or query a recordset base or Order_Date ?
using (var db = new SQLite.SQLiteConnection(ApplicationData.Current.LocalFolder.Path + "\\aaa.sqlite"))
{
// You can use any one
var list2 = db.Query<Order>("SELECT * FROM Order WHERE Order_Date = datetime('2013-10-01')", "");
var list3 = db.Query<Order>("SELECT * FROM Order WHERE Order_Date = ?", DateTime.Today.AddDays(-5));
}
How to select or query a recordset base on Date Range ? from this date to this date.
using (var db = new SQLite.SQLiteConnection(ApplicationData.Current.LocalFolder.Path + "\\aaa.sqlite"))
{
// You can use any one
var list = db.Query<Order>("SELECT * FROM Order WHERE Order_Date BETWEEN datetime('2013-10-01') AND datetime('2013-10-07')", "");
var list1 = db.Query<Order>("SELECT * FROM Order WHERE Order_Date BETWEEN ? AND ?", DateTime.Today.AddDays(-9), DateTime.Today.AddDays(-3));
}
SQLite Date And Time Functions

Go thorough bellow link
Windows Phone 7 Native Database Programming via Sqlite Client for Windows Phone
SQLite-WinRT: Database programming on Windows Phone and Windows 8
How to use SQLite in Windows Phone
Hope it will help you

Related

How to make a primary key start from 1000? sqlite.net xamarin android [duplicate]

This question already has answers here:
Set start value for AUTOINCREMENT in SQLite
(7 answers)
Closed 5 years ago.
I need the primary key to start from 1000 .how can do it?
public class LoginTable
{
[PrimaryKey, AutoIncrement, Column("_Id")]
public int id { get; set; }
public string info { get; set; }
public string info2 { get; set; }
}
You can modify the sqlite_sequence table and assign whatever starting point you want. If the LoginTable has not been inserted into, you will need to insert a new sqlite_sequence record, otherwise you would need to update the existing sqlite_sequence record.
The sqlite_sequence contains just two fields (name and seq) and does not contain a primary key nor any indexes. name is name of your table and seq is the current used sequence number, the next insert would increment this BEFORE using it.
Example:
using (var db = new SQLiteConnection("foo.sqlite"))
{
db.CreateTable<LoginTable>();
db.Execute("insert into sqlite_sequence (name, seq) values (?, ?);", new object[] { "LoginTable", 999 });
// if LoginTable records already exist, then the `sqlite_sequence` record exists for this table and you need to update it...
//db.Execute("update sqlite_sequence set seq = ? where name = ?;", new object[] { 999, "LoginTable"});
var login = new LoginTable { info = "info1....", info2 = "info2....." };
db.Insert(login);
db.Insert(login);
db.Insert(login);
foreach (var item in db.Table<LoginTable>())
{
Console.WriteLine(item.id);
}
}
Output:
1000
1001
1002

pass the value null when datetime is not filled by user

I create a function. Where date can be selected by the user . And when the user not select the date i want to pass null .
public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime startDate, DateTime endDate, string invoiceNumber, ref int totalInvoice)
{
// doing something here
}
And this is the code part where i am calling the function
_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize, clientid, Convert.ToDateTime(txtFirstDate.Text.Trim()), Convert.ToDateTime(txtLastDate.Text.Trim()), txtInvoiceNumber.Text.Trim(), ref invoicecount);
Sometime the user cant fill the txtFirstDate.Text but i am converting Convert.TodateTime() so how can i fix this because when user not fill the datetime it give me exception. So how can i handle this .
You need to change your method to:
public DataSet GetInvoicebyPaging(int pageIndex, int pageSize, Int32 clientId, DateTime? startDate, DateTime endDate, string invoiceNumber, ref int totalInvoice)
{
// doing something here
}
And when you parse the user data you can do:
DateTime? start = null;
DateTime possibleStartValue;
if(!string.IsNullOrEmpty(txtTextBox.Text) && DateTime.TryParse(txtTextBox.Text, out possibleStartValue))
{
start = possibleStartValue;
}
You can create a nullable date time variable as follows
DateTime? value = null;
and pass as a parameter
In your function you can use like DateTime? value as parameter
So you will have to do the following step
DateTime? startDate=txtFirstDate.Text.Trim()==""?null:Convert.ToDateTime(txtFirstDate.Text.Trim());
change your function argument so that it can take null value as above.
For any dates you want to be able to accept as null, like DateTime startDate you need to make them nullable like DateTime? startDate
And then before you call GetInvoicebyPaging try and sort out the datetimes.
DateTime startDate;
var correctStart = DateTime.TryParse(txtFirstDate.Text.Trim(), out startDate);
And then pass the parameter like
_orderDAC.GetInvoicebyPaging(pageIndex, grdInvoice.PageSize,
clientid, (correctStart ? startDate : null), etc
And you may have to check if txtFirstDate.Text is null as well.
After declaring startDate above you can do:
var dateString = txtFirstDate.Text ?? "";
And pass dateString.Trim() into the DateTime.TryParse

Insert record using entity Framework (database first)

there are 3 database tables (movies, reviews, users)
the reviews table include ( MemeberID, MovieID, Review Text, Rate, ReviewDate)
(the MemeberID, and MovieID in the Review are the FK of the members table and the movies table)
The Movie can have many reviews, and i'm trying to add review to a movie
even I have movie class and the member class, I have a problem, in order to insert review, i need to reference it to movie and users , link them, and i don't know how to do it
this code make a error:
" The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects. "
This is my code...
public bool InsertNewReview(Movie _TheMovie, Member _TheMember, string _Text, byte _Rate, DateTime _ReviewDate)
{
Review ReviewToInsert = new Review()
{
MovieID = _TheMovie.MovieID,
MemberID = _TheMember.MemberID,
Movie = _TheMovie,
Member = _TheMember,
Rate = _Rate,
ReviewDate = _ReviewDate,
ReviewText = _Text
};
videoLib.Reviews.AddObject(ReviewToInsert);
videoLib.SaveChanges();
return true;
}
..
there are more data to insert to the Review class
Images: here
..
and the tables: (the "all columns" isn't a field in database tables)
Images: here
could you try like this
Review ReviewToInsert = videoLib.Reviews.CreateObject();
ReviewToInsert.MovieID = _TheMovie.MovieID
...
...
videoLib.Reviews.AddObject(ReviewToInsert);
videoLib.SaveChanges();
I got a solution, I need to define only the MovieID, MemberID, and not using their object
and use try & catch, to detect if thier the same MovieID (fk) and MemberID (fk) in the same row (because the review don't have is own id in the database)
public bool InsertNewReview(string _MovieID, int _MemberID, string _Text, byte _Rate, DateTime _ReviewDate)
{
try
{
Review ReviewToInsert = new Review()
{
Rate = _Rate,
ReviewDate = _ReviewDate,
ReviewText = _Text,
MovieID = _MovieID,
MemberID = _MemberID
};
videoLib.Reviews.AddObject(ReviewToInsert);
videoLib.SaveChanges();
return true;
}
catch
{
return false;
}
}

RavenDB query by index and DateTime

I'm quite new to RavenDB so sorry if my question sounds stupid. I have a class which contains a DateTime property. I store instances of this class in RavenDB. I have defined index the following way:
from doc in docs.Orders
from docItemsItem in ((IEnumerable<dynamic>)doc.Items).DefaultIfEmpty()
select new { Items_Price_Amount = docItemsItem.Price.Amount, Items_Quantity = docItemsItem.Quantity, Date = doc.Date }
http://dl.dropbox.com/u/3055964/Capture.GIF <-- here's a screenshot
Here's class definition:
public class Order
{
public DateTime Date { get; set; }
public IList<OrderItem> Items { get; set; }
public string CustomerId { get; set; }
public Order()
{
Items = new List<OrderItem>();
}
}
Now, when I try to query RavenDB with the index shown above, the query yields no result at all.
var orders = session.Query<Order>("OrdersIndex").Where(o => o.Date > DateTime.Now).ToList(); // orders.Count == 0
If I omit the index from query, like this:
var orders = session.Query<Order>().Where(o => o.Date > DateTime.Now).ToList(); // orders.Count == 128
a temporary index is created and eveything works as expected.
Does anyone has any idea what's wrong with my query?
Thanks.
UPDATE
Allright, I removed Fields Date, Items,Price,Amount and Items,Quantity via management studio (shown in screenshot), and now the query works fine. Anyone any idea why? What's the purpose to define those fields explicitly?
Check that the date in the Index is stored as Index(x => x.Date, FieldIndexing.Default).
I had it set to FieldIndexing.Analysed, and wasn't getting the correct results back.
I need to read up more on the difference between the different FieldIndexing options :)

Linq2EF: Return DateTime with a TimeZone Offset

Our database has all times stored as UTC, and we know the user's current timezone, so want to return it relative to that. So we want to incorporate the offset in a LINQ projection as so:
var users = from u in this.Context.Users
select new UserWithCorrectedDate
{
Id = u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
RegistrationDate = u.RegistrationDate.Value.AddHours(-5)
};
Of course, Linq2EF cannot convert "AddHours" into a canonical function. Is there another way to do this?
UPDATE:
Another thought, if the timezone offset was stored in the database as another column, would there be a way to have the DB perform the calculation (date + offset)?
Linq to Entities supports SqlFunctions. If you know the offset number of hours you could do something like this:
var users = from u in this.Context.Users
select new UserWithCorrectedDate
{
Id = u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
RegistrationDate = SqlFunctions.DateAdd("hour", -5, u.RegistrationDate.Value)
};
If you want to be more precise by using the Timezone function, you could do something like this (this is a bit of a workaround):
public static DateTime UtcToNewYorkTime(DateTime utcDateTime)
{
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime converted = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tzi);
return converted;
}
And then in your POCO UserWithCorrectedDate object, have a get only property for the Timezoned date ie.
public class UserWithCorrectDate
{
public DateTime UTCDate {get;set;}
public DateTime NYDate
{
get
{
return Utilities.UtcToNewYorkTime(this.UTCDate);
}
}
}
The quick and dirty way to do this is to convert to a list, and just linq to object to get it done:
from u in this.Context.Users.ToList()
select new { ... }

Resources