2012-09-12 44 views
0

我試着同時在多線程數據庫上寫數據
但myCommand.Connection.Open()中發生錯誤;
錯誤:未將對象引用設置爲對象的實例。
我該如何解決這個問題?同時在數據庫中插入多行數據c#

這個例子說明問題

private void button1_Click(object sender, EventArgs e) 
    { 
     new Thread(() => 
     { 
      SqlCommand myCommand = new SqlCommand("insert into table(a,b)values(1,'aaa')", Connection); 
      myCommand.Connection.Open(); 
      myCommand.ExecuteNonQuery(); 
      myCommand.Connection.Close(); 
     }).Start(); 
     new Thread(() => 
     { 
      SqlCommand myCommand = new SqlCommand("insert into table(a,b)values(2,'aaa')", Connection); 
      myCommand.Connection.Open(); 
      myCommand.ExecuteNonQuery(); 
      myCommand.Connection.Close(); 
     }).Start(); 
     new Thread(() => 
     { 
      SqlCommand myCommand = new SqlCommand("insert into table(a,b)values(3,'aaa')", Connection); 
      myCommand.Connection.Open(); 
      myCommand.ExecuteNonQuery(); 
      myCommand.Connection.Close(); 
     }).Start(); 
     new Thread(() => 
     { 
      SqlCommand myCommand = new SqlCommand("insert into table(a,b)values(4,'aaa')", Connection); 
      myCommand.Connection.Open(); 
      myCommand.ExecuteNonQuery(); 
      myCommand.Connection.Close(); 
     }).Start(); 
    } 
+0

「Connection」來自哪裏? – dasblinkenlight

+0

這會對服務器造成瓶頸...... – MoonKnight

+0

@Killercam在數據庫中同時插入多行的最佳方法是什麼c# – motaz99

回答

2

你需要一個有效的連接:

SqlConnection connection = new SqlConnection(...); 
connection.Open(); 

SqlCommand command = new SqlCommand(...); 
command.Connection = connection; 
command.ExecuteNonQuery(); 
+0

我無法描述我該如何感謝你 – motaz99

+0

不客氣! :) – Alessandro

0

不清楚爲什麼你需要/想這樣做,在SQL2K8你可以簡單地使用表值構造函數單行< 1k行;

insert into table(a,b)values(1,'aaa'),(2,'aaa'),(3,aaa)

+0

這不是那麼簡單我在我的項目中有多線程,並且÷想要插入每個線程與其他線程不同 – motaz99