0

我尝试同时在多线程中写入数据库,
但错误发生在 myCommand.Connection.Open();
错误:对象引用未设置为对象的实例。
我怎么解决这个问题 ?

这个例子显示了问题

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();
    }
4

2 回答 2

2

您需要一个有效的连接:

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

SqlCommand command = new SqlCommand(...);
command.Connection = connection;
command.ExecuteNonQuery();
于 2012-09-12T12:47:13.270 回答
0

不清楚为什么需要/想要这样做,在 SQL2K8 中,您可以简单地在单个批次中使用表值构造函数来处理 < 1k 行;

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

于 2012-09-12T12:57:21.440 回答