同时在数据库中插入多行c#

时间:2012-09-12 12:45:17

标签: c# sql-server multithreading

我尝试在多线程中同时写入数据库 但错误发生在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();
    }

2 个答案:

答案 0 :(得分:2)

您需要有效的连接:

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

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

答案 1 :(得分:0)

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

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