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