sir_thursday
sir_thursday

Reputation: 5419

Using C# to loop through and insert data

I have a program that has to loop through a Scenarios database, and for each while loop iteration, update a second Results database. Here's the segment of code.

    public void TestScenarios(SqlConnection connection)
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Scenarios", connection))
        {
            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    string Id = reader["ScenarioID"].ToString();
                    string Data = reader["ScenarioData"].ToString();
                    string Url = reader["ScenarioURL"].ToString();
                    webBrowser1.Navigate(Url);
                    InsertResults(connection, Id);
                }
            }

            reader.Close();
        }
    }

    public void InsertResults(SqlConnection conn, string Id)
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO Results VALUES(" +
                "@ResultID, @HasSucceeded, @ScenarioID, @Screenshot)", conn))
        {
            cmd.Parameters.AddWithValue("@ResultID", 0);
            cmd.Parameters.AddWithValue("@HasSucceeded", 0);
            cmd.Parameters.AddWithValue("@ScenarioID", Id);
            cmd.Parameters.AddWithValue("@Screenshot", "screenshot.jpeg");
        }
    }

It's not working, and I'm sure I did tons of things wrong, but I'm having trouble finding direction.

Upvotes: 2

Views: 3803

Answers (2)

Mechanical Object
Mechanical Object

Reputation: 666

May I propose you to use SqlBulkCopy? Here is some information on how to copy two database tables , I hope you'll find it clear.

http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy%28v=vs.90%29.aspx

Upvotes: 2

Bill Gregg
Bill Gregg

Reputation: 7147

Your second command is never executing. Add:

cmd.ExecuteNonQuery();

Upvotes: 5

Related Questions