Reputation: 504
I've recently started learning some databases things in .NET (C#) and I have a problem with inserting list of objects into local database. I don't know the reason but, after executing query, base is still empty and there is no error or warning, can you tell me if there is any problem with the code, or is there any other reason why it does not work properly.
I've tried to debug, but code seems to work, it passes if statement, and adds parameter's value, I've also removed thread start method and did it synchronously but still nothing.
public static void SaveData()
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Przestoje(Urzadzenie, Czas, Data) VALUES(@nazwa, @czas, @data)", conn))
{
cmd.Parameters.AddWithValue("@nazwa", SqlDbType.NVarChar);
cmd.Parameters.AddWithValue("@czas", SqlDbType.Int);
cmd.Parameters.AddWithValue("@data", SqlDbType.NVarChar);
int count = allEncounters.Count;
for (int i = 0; i < count; i++)
{
if (i >= NextIndex)
{
cmd.Parameters["@nazwa"].Value = allEncounters[i].Name;
cmd.Parameters["@czas"].Value = allEncounters[i].timeOnTimeout * 10;
cmd.Parameters["@data"].Value = allEncounters[i].startDate.ToString();
}
}
NextIndex = count;
}
}
}).Start();
}
Upvotes: 0
Views: 148
Reputation: 45096
You can trim that down
for (int i = NextIndex; i < allEncounters.Count; i++)
{
cmd.Parameters["@nazwa"].Value = allEncounters[i].Name;
cmd.Parameters["@czas"].Value = allEncounters[i].timeOnTimeout * 10;
cmd.Parameters["@data"].Value = allEncounters[i].startDate.ToString();
cmd.ExecuteNonQuery();
}
NextIndex = allEncounters.Count;
Upvotes: 1
Reputation: 11573
You have to execute the SqlCommand. Put this before "NextIndex = count;":
cmd.ExecuteNonQuery();
Upvotes: 1
Reputation: 218827
At some point you have to actually execute the SQL command, which you currently don't do:
cmd.ExecuteNonQuery();
If you're looking to insert one record, this would be near the end. Though it looks like you're trying to insert multiple records in a loop, so this would of course happen inside the loop. (Once per record.)
Upvotes: 4