I am retrieving data from Sqlite database using the following query in c#
SELECT * FROM tableName
It works fine. But I want to retrieve data on the basis of date like:
SELECT * FROM tableName WHERE date=09-09-2013
But it do not works for me because Sqlite date representation is not in this date format.
What i want to ask is that is there any method by which Sqlite data can be retrieved on the basis of user date and time like mentioned in above query and how can I represent date and time of Sqlite database in user readable format.
A parameterized query would free your code from the formatting required for date, strings and decimals by various database engines
using (SqliteConnection con = new SqliteConnection(connectionString))
{
con.Open();
string commandText = "SELECT * FROM tableName WHERE date=#dt";
using (SqliteCommand cmd = new SqliteCommand(commandText, con))
{
cmd.Parameters.AddWithValue("#dt", yourDateVariable)
SqliteReader reader = cmd.ExecuteReader();
while(reader.Read())
{
// Extract your data from the reader here
.....
}
}
}
The point of this example is to show how to build a parameterized query. In this way you pass the value of your datetime variable to the framework of Sqlite engine that knows better how to format a date for the underlying system.
In the commandText variable the actual formatted value for the date is taken by the placeholder #dt, then add, to the SqliteCommand Parameters collection, a parameter with the same name of the placeholder and the value from your date variable.
Related
In windows form I have DateTimePicker with custom format dd/MM/yyyy.
I want to insert the selected date to SQL Local DB but it throwing an exception.
Conversion failed when converting date and/or time from character string
my question is:
How to insert this date into a database in any format.
Here is my code
string query = "Insert into myTable Values('" + dateTimePicker1.Text + "');";
Use DateTimePicker.Value instead of DateTimePicker.Text. If you only want the date part, you could use DateTimePicker.Value.Date.
DateTimePicker.Value is the actual DateTime object assigned to the control, whereas DateTimePicker.Text is the Value property with formatting applied. Using Value directly saves you from having to convert the Text to a DateTime first.
You should also use a parameterized query, as others have noted.
string query = "Insert into myTable Values (#myDate)";
using(SqlConnection connection = new SqlConnection(connectionString))
{
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("myDate", dateTimePicker1.Value);
}
}
In my app, I am trying to grab a date from the database and compare it against local time. Right now I am getting an error when I am converting to date incorrectly.
I have tried:
Convert.ToDateTime()
DateTime.ParseExact()
My code:
string time = "Select top(1) DATE from SERVICE order by DATE desc";
SqlCommand command = new SqlCommand(time, connection);
connection.Open();
using (SqlDataReader timereader = timecommand.ExecuteReader())
{
while (timereader.Read())
{
if (DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss", null).AddMinutes(10) > currenttime)
{
// code
}
}
connection.Close();
}
I am hoping when I retrieve this value from the database, I can convert it into a proper datetime value and compare against local time and run other code after that.
At the moment I am just getting this error:
The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
I'm probably just dumb and missing something obvious..
Your query selects a single value. Use ExecuteScalar and cast it to a DateTime (it's already a DateTime, but boxed inside an object):
string time = "Select top(1) DATE from SERVICE order by DATE desc";
SqlCommand command = new SqlCommand(time, connection);
connection.Open();
DateTime d = (DateTime)command.ExecuteScalar();
connection.Close();
After you do this, and before you embark on some long mission of this protracted way of getting data out of a database, converting it to objects for use in your app etc, take a look at least at an ORM called Dapper, if not Entity Framework. Dapper's basically what you're doing now, but it auto converts your queries to objects and back and saves a lot of tedious code. With Dapper it'd look more like:
using (var connection = new SqlConnection("connstr"))
{
var d = connection.QuerySingle<DateTime>("SELECT TOP 1 Date FROM ...");
}
Yes, it's not much of a saving over what you have now, right? But what if you have a list of Order that themselves have 20 properties:
using (var connection = new SqlConnection("connstr"))
{
var orders = connection.Query<Order>("SELECT * FROM order WHERE customerID = #custid", new {custid = 123}).ToList();
}
Orders is now a list of Order objects for customer 123, parameterized, injection safe, quick and a one liner to read and populate your orders; doing that in a datareader is going to take at least 25 lines of boring code
http://dapper-tutorial.net and spend 2 minutes reading; I'll lay bets you'll be glad you did
Just try to read the value as a proper, native DateTime type like this (assuming that the DATE column in SQL Server is in fact a DATETIME or similar datatype - not a string - hopefully!):
using (SqlDataReader timereader = timecommand.ExecuteReader())
{
while (timereader.Read())
{
// just read the DateTime value as such
DateTime dt = timereader.GetDateTime(0);
// then do whatever you need to do with this DateTime value .....
}
connection.Close();
}
Is this possible with ms access data type?
I need to merge mdb files. The twist is i doesn't know the table names and the data type.
I'm now in the part of merging data. What i did is i retrieve the data first then save in the merged mdb file.
Here is my code
string SqlString = "Insert Into Contacts (data1, data2) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("data1", "data1");
cmd.Parameters.AddWithValue("data2", "data2");
conn.Open();
cmd.ExecuteNonQuery();
}
}
With the code above i can save the data using if the data type is text. But when the data type is int and the data i passed is string but can be parsed as number the gives me Data type mismatch in criteria expression.
If i'm going to parse number. How about the Date/Time format? I check the database and it's also one of the error. How can i pass null into this? i checked the value and it's blank.
I have DateTimePicker object in a C# winform application, from which I am getting date and time in yyyy-MM-dd HH:mm tt custom format. But whenever I save the data in phpmyadmin, it gets saved as "0000-00-00 00:00:00.000000" in the specific field. My code is bellow:-
private void submit_Click(object sender, EventArgs e)
{
DateTime scd = MydateTimePicker.Value;
cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into flight(flight_schedule) values ('" + scd + "')";
cmd.ExecuteNonQuery();
cn.Close();
}
In c# when you use a DateTime variable in a string context, it is treated as if it were appended with .ToString(). Unfortunately that delivers a locale-specific rendering of the date. On my USA locale it looks like this:
2/26/2016 7:12:19 PM
MySQL, when you present datetime values to it as strings, needs this format.
2016-02-26 19:12:19
In some versions of MySQL, a failure to interpret a date results in a zero date. Read this for more information on that topic. http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_allow_invalid_dates
Your insert query constructs a query string, so your DateTime value gets formatted in a way that MySQL cannot use. That's why you get that strange zero date.
If you changed your insert query to this, things would probably start to work.
cmd.CommandText = "insert into flight(flight_schedule) values ('" +
scd.ToString("yyyy-MM-dd HH:mm:ss") + "')";
Better yet, use parameters. Read this for an example and discussion. C# SqlParameters Short Hand
No.
You have a bad habit to kick as choosing wrong data type. You should never store your DateTime values as a string.
Change your flight_schedule to DATETIME column type and pass your DateTime value directly with a parameterized query.
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
using(var cn = new MySqlConnection(conString))
using(var cmd = cn.CreateCommand())
{
cmd.CommandText = "insert into flight(flight_schedule) values (#date)";
cmd.Parameters.Add("#date", MySqlDbType.Datetime).Value = MydateTimePicker.Value;
// I assume you change your column type to Datetime
cn.Open();
cmd.ExecuteNonQuery();
}
EDIT:
Looks like you already have DATETIME column in your database, so my answer seems irrelevant but I still believe saving your DateTime as their values, not their string representations.
I'm trying to insert data of type 'date' from a textbox on my form to the database.
I want to ensure data entered by the user is stored in the format'dd/mm/yyyy' in the database. I have a column in the database of type 'date' but when i enter values of the format above, i get an exception (something like: cannot implicitly convert varchar to type date).
Please how do I convert date entered to the format 'dd/mm/yyyy'. I tried using CONVERT((varchar,getdate(),103) AS [DD/MM/YYYY]) but i cant figure out where to place it in my code. I'm new to c# and sql server, help please!!
It's better to not convert the date in SQL, and just pass it back as a date, and then within C# you can structure it however you want
myDate.ToString("dd/mm/yyyy")
use parameterised queries:
DateTime dt;
dt = DateTime.ParseExact(TextBox1.Text,
"dd/MM/yyyy",CultureInfo.InvariantCulture);
SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "INSERT INTO [TABLENAME](DateCol) VALUES(#DateValue)";
SqlCommand cmd=new SqlCommand(query,con);
cmd.Parameters.AddWithValue("#DateValue",dt);
con.Open();
cmd.ExecuteNonQuery();
EDIT: from your comments :
i want the date to also be displayed in the same 'dd/MM/yyyy' format
in the database
You can can not control underlying Database how it displays or manages your Date in Database but if you want to get the date in format of dd/MM/yyyy while reading from database you can try the below:
SqlCOnnection con=new SqlConnection("/*connection string here*/");
string query = "SELECT [DateCol] FROM TABLENAME]";
SqlCommand cmd=new SqlCommand(query,con);
con.Open();
SqlReader reader = cmd.ExecuteReader();
while(reader.Read())
{
DateTime dt= Convert.ToDateTime(reader["DateCol"].ToString());
string mydateString = dt.ToString("dd/MM/yyyy");
}
con.Close();