I was trying to make excel graphs using query in c# and I need to collect data for the last month. I am using the following code and its not giving any error but its not giving any result either.
Basicaly I have the data in excel sheets and using that data im making graphs.
First im geting the two dates and converting them to short string and then im matching the strings with the dates picked from excel in the short strong format.
If anyone could answer, I would really appreciate help.
Thankyou,
THE CODE:
// Get current date and time
DateTime dtx = DateTime.Now;
string Date = dtx.ToShortDateString();
// Calculating the last month's date (substracting days from current date.)
DateTime lastmonth= DateTime.Today.AddDays( -30 );
string Date2 = lastmonth.ToShortDateString();
OleDbCommand objCmdSelect = new OleDbCommand(
"SELECT [Hour],(Format(Date, 'Short Date')) AS text_Date,[U_CSSR] FROM [" + excelSheets[j] + "] WHERE CI=" + id + " AND (Format(Date, 'Short Date'))BETWEEN "+ Date + " AND "+ Date2 + " ", objConn);
I think your WHERE clause is logically incorrect. it should be
... BETWEEN "+ Date2 + " AND "+ Date ...
The earlier date should come first.
BETWEEN a AND b is equal to: x > a and x < b.
Related
Help as early as possible please
I have a form in which I add Exhibitions in the museum name, the date through the Datetimepicker and people came up and then they are saved in the sql database And then on another form I want to select 2 dates in two Datetimepickers and to show in the datagrid that there are some exhibitions between two dates BUT it does not show me correctly, I can not even explain whats wrong
private void button3_Click(object sender, EventArgs e)
{
string period = "SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString() + "' AND '" + dateTimePicker2.Value.ToString() + "'";
LoadData(period);
dataGridView2.Columns[0].Visible = false;
/*dataGridView2.Columns[1].Visible = false*/;
dataGridView2.AllowUserToAddRows = false;
button1.Enabled = true;
}
is it right?
i want it show like events between 12.November.2020 and 21.December.2020
I think you can just use the answer from this question here.
Basically, you just need to feed it the proper format:
string period = "SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss.fff") + "' AND '" + dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
For bonus points you could also switch to using string interpolation to make it more readable.
string period = $"SELECT* FROM vistavka WHERE Date BETWEEN '{dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")} ' AND '{dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")} '";
Update:
Please check out this on why doing it this way is a security problem.
Then learn about SQL parameters here.
And finally you can see this answer for how to do date parameters. Basically, you shouldn't have to convert a C# datetime to a string just to pass it into SQL. C# already has mechanisms for this and for good reason, as you'll see in those links.
the date to string convertion was used is wrong
"SELECT* FROM vistavka WHERE Date BETWEEN '" + dateTimePicker1.Value.ToString() + "' AND '" + dateTimePicker2.Value.ToString() + "'";
ToString() format is culture depended and should not be used
You have to pass SQL query with parameters and parameter values (as DateTime objects) to convert date from DateTime by SQL client API to the parameter value format used by your SQL server.
Please find MS SQL sample here
I'm trying to run a query that selects all from a table that contains a DateTime. At the DateTime, it uses a DateTime variable (argument passed through the parameter), however it gives me this exception:
"FormatException was unhandled
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: The string was not recognized as a valid datetime"
Solutions I've tried, but didn't work:
Convert the DateTime to string
Convert the DateTime to string with correct format and then back to
DateTime again
Use the DateTime.Parse method
Use the DateTime.ParseExact method with correct format and using both
"CultureInfo.InvariantCulture" and "CreateSpecificCulture("en-GB")
Change the format to the exact same shown when running the query in
Database
As said, none of the above have worked..
The format I try to use: "MM/dd/yyyy 00:00:00"
Format shown when running query in database: "MM/dd/yyyy
hh:mm:ss:fff" (the time needs to be set to 00:00:00)
Here is the code with the connection stuff excluded:
cmd = new SqlCommand("SELECT * FROM Arithmetics "
+ "INNER JOIN ArithmeticsAndTypeIDs "
+ "ON Arithmetics.ArithmeticID = ArithmeticsAndTypeIDs.ArithmeticsID "
+ "INNER JOIN ArithmeticTypes "
+ "ON ArithmeticsAndTypeIDs.TypeID = ArithmeticTypes.TypeID "
+ "WHERE UserID = #value1 "
+ "AND TimeStamp >= '#value2' "
+ "AND TimeStamp <= '#value3'", con);
cmd.Parameters.AddWithValue("#value1", GetUserID(userLoggedIn));
cmd.Parameters.AddWithValue("#value2", DateTime.ParseExact(time.ToString(), formatString, CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat));
time = time.AddDays(1);
cmd.Parameters.AddWithValue("#value3", DateTime.ParseExact(time.ToString(), formatString, CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat));
The problem first occurs at the line: "+ "AND TimeStamp >= '#value2' ""
* And in case it makes a difference, here is the quote I use in the database which obv. works (with the variables replaced by placeholder values)
SELECT * FROM Arithmetics
INNER JOIN ArithmeticsAndTypeIDs
ON Arithmetics.ArithmeticID = ArithmeticsAndTypeIDs.ArithmeticsID
INNER JOIN ArithmeticTypes
ON ArithmeticsAndTypeIDs.TypeID = ArithmeticTypes.TypeID
WHERE UserID = 0
AND
ArithmeticTypes.TypeID = 2
AND TimeStamp >= '09-21-2016 00:00:00'
AND TimeStamp <= '09-22-2016 00:00:00'
It should be noted that "#value2" contains the value ("09-21-2016 00:00:00") (assuming that's the date that is passed as a parameter), so I know that the formatting is correct.
Any help towards fixing this issue would be greatly appreciated :)
You don't need to convert parameters to strings. That's one of the main reason they are used instead of string concatenation. As long as TimeStamp is a date-related type, your query should be :
WHERE UserID = #value1 AND TimeStamp BETWEEN #value2 and #value3
Parameter values should be passed without any conversion to string:
cmd.Parameters.AddWithValue("#value1", GetUserID(userLoggedIn));
cmd.Parameters.AddWithValue("#value2", time);
cmd.Parameters.AddWithValue("#value3", time.AddDays(1));
Parameters are passed by the driver itself in a binary form, so they don't have to be converted to text. This way you bypass any formatting or localization issues.
You also avoid SQL injection issues because the parameter values are never part of the query. Even string variables are treated as just text, they are never part of the query.
I am trying to insert current time to a Time column in the excel using the below code through an oledb connection but when I check the excel the value inserted is in Date format.
Value updated in excel - 1/0/1900 3:54:11 PM
Expected Value - 3:54:11 PM
string currentTime = DateTime.Now.ToString("hh:mm:ss.fff tt");
string cmnd1 = "Create Table [" + currentDate + "] (TestCase char(100), ExecutionTime Time, Result char(20))";
string cmnd2 = "Insert Into [" + currentDate + "] (TestCase, ExecutionTime, Result) values ("+ "'" + tName + "',#dd,'" + result +"')" ;
using (OleDbConnection conn = new OleDbConnection(ConnectionStringtd))
{
OleDbCommand createSheet = new OleDbCommand(cmnd1, conn);
OleDbCommand insertResult = new OleDbCommand(cmnd2, conn);
insertResult.Parameters.AddWithValue("#dd", DateTime.Now.TimeOfDay);
conn.Open();
try
{
createSheet.ExecuteNonQuery();
}
catch(OleDbException) {}
insertResult.ExecuteNonQuery();
}
}
AFAIK, when you enter pure time value stored as a datetime with the entered time portion, and a date part will be January 0, 1900 automatically since the days before 1900 are incorrect in Excel.
Instead of that, pass your DateTime.Now directly to parameter and change your column format type to Time with h:mm:ss tt format in your format cells part. By the way, you just paramterized #dd part. Use parameters for the other values that you try to insert. Don't concatenate them.
insertResult.Parameters.AddWithValue("#dd", DateTime.Now);
And don't use AddWithValue anymore. It may generate unexpected and suprising results sometimes. Use Add method overload to specify your parameter type and it's size.
Also use using statement to dispose your commands as you did for the connection.
I'm trying to update a DATE (not DATETIME) column in SQL Server, but when I execute the SQL command, it is posted with time format also.
string datetosql = "10.4.2015";
string sqlQuery = "UPDATE tbl_tasks " +
"SET description = '" + tbTaskDescription.Text + "', " +
"deadline = '" + datetosql + "' , " +
"status = '" + statusIndex.ToString() + "' " +
"WHERE tid = " + _TaskID;
When I later collect the date using SqlDataReader, it is posted with time format: 04.10.2015 00:00:00. Why is this happening?
.NET doesn't have a date only data type.
If you ask to return a SQL Server date, or a time, it always returns a DateTime struct instance in .NET. For a date, the time properties (hours, minutes, etc.) will be 0.
Note that using queries that aren't parameterized is considered bad! You are open for SQL injection, and you make your life harder since you need to escape quotes, etc.
Add a cast to datetosql, ex:
Cast(datetosql as Date)
I have 2 project, one is CRUD class and another is contain a WinForm that will access the CRUD class.
Here come my problem, everytime i trying to insert DateTimePicker with default value in MYSQL with datetime column type, i getting 0000-00-00 00:00:00 Zero zero zero and zero value, what i missed here?
Here is my part of CRUD class code, my CRUD class named DBConnect.cs
public DateTime property_dtDate { get; set; }
sqlQuery = "INSERT INTO master (NoInvoice, Name, Date, Type, Additionaltext) VALUES ('" + property_NoInvoice + "', '" + property_sName + "', '" + property_dtDate + "', '" + property_sType + "', '" + property_sAdditionalText + "')";
And here is my part of WinForm code, which is i named it Form1.cs (both is in separated project)
clsDbConnect.property_dtDate = DateTime.Parse(datetimepicker1.Value.ToString("yyyy-MM-dd HH:mm:ss"));
clsDbConnect.Insert();
I try look at the value with messagebox, a value that pass through my WinForm is good, nothing suspicious, it show the every date and time which is right know, but when i looked in my database, all i got is 0000-00-00 00:00:00. I don't have any clue what cause that, help me to find out please
I think you have a problem because of string format of the datetime. MySQL not understand your string format as a datetime value.
Try use parameters(assume somewhere in code you have a SqlCommand object):
string query = "INSERT INTO master (NoInvoice, Name, Date, Type, Additionaltext) VALUES (#NoInvoice, #sName, #dtDate, #sType, #sAdditionalText)";
using(SqlCommand command = New SqlCommand(query, yourconnection)
{
command.Parameters.AddWithValue("#NoInvoice", property_NoInvoice);
command.Parameters.AddWithValue("#sName ", property_sName);
command.Parameters.AddWithValue("#dtDate ", property_dtDate);
command.Parameters.AddWithValue("#sType ", property_sType);
command.Parameters.AddWithValue("#sAdditionalText ", property_sAdditionalText);
command.ExecuteNonQuery();
}
Using parameters help with type safety(datetime and numerics format issues) and prevent a SQL injection vulnerability.
Then when you don't need to parse a datetimepicker's value to type DateTime because ti is already DateTime (From MSDN: DateTimePicker.Value)
clsDbConnect.property_dtDate = datetimepicker1.Value;