C# SQL insert command

后端 未结 5 1783
小蘑菇
小蘑菇 2020-12-01 13:35

Can anyone tell me the following 2 ways of inserting record creates better performance?

Case 1

SqlCommand cmd = new SqlCommand();

f         


        
5条回答
  •  遥遥无期
    2020-12-01 14:17

    It should be noted exactly that as-is, neither case will work.

    Case #1 requires a connection to be specified.

    Case #2 requires you to end your statements with a semi-colon in order to run multiple commands, like so:

    string sql = null;
    
    for (int i = 0; i < 10000; i++)
    {
      sql += "insert into test(id, name) value('" + i + "', '" + i + "');";
    }
    
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.ExecuteNonQuery();
    

    Ultimately the best way would be for you to just test it yourself on several thousand rows. My guess would be that the Case #2 would be better for performance because not only would it require setting up only a single SqlCommand object, but it only hits the database a single time.

提交回复
热议问题