Question

I'm trying to make a program that copies data from one table to the other in other server.

The thing is table is not exactly same. So Let's say these are my tables:

Server A: TableA (Col1, Col2, Col3)

Server B: TableB (Col1, Col2)

I want to copy from ServerA.TableA to ServerB.TableB.

My code:

Truncate_table(ConnectionB, "TableB");

MySqlCommand CmdB = new MySqlCommand("", ConnectionB);
CmdB.CommandText = "INSERT INTO ServerB.TableB (col1, col2) VALUES (@val1, @val2)";

using (MySqlCommand cmd = new MySqlCommand("", ConnectionA))
{
    cmd.CommandText = "SELECT col2, col3 FROM ServerA.TableA";

    using (MySqlDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            CmdB.Parameters.AddWithValue("@val1", reader.GetInt32(0));
            CmdB.Parameters.AddWithValue("@val2", reader.GetInt32(1));
            CmdB.ExecuteNonQuery();
        }

    }
}

However, it gives error saying 'Parameter '@val1' has already been defined.'.

Can you guys give me a piece of advice?

And is there more efficient way to do this? but I want to do this in C#.

Was it helpful?

Solution

Try adding the parameters once, then setting the value of those parameters within the while-loop:

MySqlCommand CmdB = new MySqlCommand("", ConnectionB);
CmdB.CommandText = "INSERT INTO ServerB.TableB (col1, col2) VALUES (@val1, @val2)";
CmdB.Parameters.AddWithValue("@val1", 0); // Default values
CmdB.Parameters.AddWithValue("@val2", 0);

using (MySqlCommand cmd = new MySqlCommand("", ConnectionA))
{
    cmd.CommandText = "SELECT col2, col3 FROM ServerA.TableA";

    using (MySqlDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            CmdB.Parameters["@val1"].Value = reader.GetInt32(0));
            CmdB.Parameters["@val2"].Value = reader.GetInt32(1));
            CmdB.ExecuteNonQuery();
        }

    }
}

Also, I could be wrong, but I believe you need to use ? to delimit parameters for MySql. If you have any other issues you might try replacing @val1 and @val2 with ?val1 and ?val2.

OTHER TIPS

You are coping row by row the data. This is a very inefficient way to copy from a table to another. You can achieve the same result with a similar code executing just one INSERT on the database, you just need to read previously all the rows you want to insert.

Oh I just added

CmdB.Parameters.Clear();

After

CmdB.ExecuteNonQuery();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top