The first, and most obvious, problem is that you're using string concatenation to build your query. In
this particular instance, since you're only dealing with known values that you've generated, it's not a huge problem. However, if you're using this pattern anywhere else, particularly where the parameters are provided by the user, it will be susceptible to
SQL Injection[
^].
Change your code to use a parameterized query. Not only will it fix the problem with passing a date parameter, but by getting out of the habit of using string concatenation to build your queries, you won't have a nasty surprise later on when
Bobby Tables[
^] uses your application. :)
The second problem is that your loop assumes 31 days for
every month. As soon as you get to February, your
DateTime.ParseExact
call will fail.
Try something like this:
using (SqlCommand insertQuery = new SqlCommand("INSERT INTO GCMemory(AgentID, GCTitle, GCProcessName, GCWindowHandle, GCMemory, DTime) VALUES (@AgentID, @GCTitle, @GCProcessName, @GCWindowHandle, @GCMemory, @DTime)", myConnection))
{
insertQuery.Parameters.AddWithValue("@AgentID", 1);
insertQuery.Parameters.AddWithValue("@GCTitle", "Inbox (312) - mayooran99@gmail.com - Gmail - Google Chrome");
insertQuery.Parameters.AddWithValue("@GCProcessName", "chrome");
var GCWindowHandle = insertQuery.Parameters.Add("@GCWindowHandle", SqlDbType.Int);
var GCMemory = insertQuery.Parameters.Add("@GCMemory", SqlDbType.Int);
var DTime = insertQuery.Parameters.Add("@DTime", SqlDbType.DateTime);
DateTime theDate = new DateTime(2013, 1, 1);
while (theDate.Year == 2013)
{
GCWindowHandle.Value = r.Next(1, 184467440);
GCMemory.Value = r.Next(1, 1000000000);
DTime.Value = theDate;
insertQuery.ExecuteNonQuery();
DateTime nextDate = theDate.AddMinutes(1);
if (nextDate.Month != theDate.Month)
{
Console.WriteLine("one month done");
}
else if (nextDate.Day != theDate.Day)
{
Console.WriteLine("one day done");
}
theDate = nextDate;
}
}