数据库正被另一个进程使用......但是什么进程?

Gar*_*ath 5 c# sql-server visual-studio-2010

我编写了一个非常小的C#程序,它使用一个非常小的SQL Server数据库,纯粹用于一些学习和测试目的.数据库用于这个新项目,而不是其他任何地方.但是,我在运行程序无法运行的Debugs时遇到问题,因为数据库"正被另一个进程使用".

如果我重新启动我的机器,它将再次工作,然后经过几次测试运行后,我将再次遇到同样的问题.

我发现在互联网上报告了许多类似的问题,但是如何解决这个问题却找不到明确的答案.首先,我如何找出使用我的.mdf和.ldf文件的"其他进程"?然后,我如何获得这些文件并且不被保留以便一次又一次地停止这种发生的时间?!?

我是VS2010,SQL Server和C#的新手,所以请在你给我的任何回复中描述一下!

这是我的代码,正如你所看到的,你无法获得更基本的东西,我当然不应该遇到这么多问题!

namespace MySqlTest
{
    public partial class Form1 : Form
    {
        SqlConnection myDB = new SqlConnection(@"Data Source=MEDESKTOP;AttachDbFilename=|DataDirectory|\SqlTestDB.mdf;Initial Catalog=MySqlDB;Integrated Security=True");
        SqlDataAdapter myDA = new SqlDataAdapter();
        SqlCommand mySqlCmd = new SqlCommand();

        string mySQLcmd;
        int myCount;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("myDB state = " + myDB.State.ToString());
            //Open SQL File
            myDB.Open();
            MessageBox.Show("myDB state = " + myDB.State.ToString());
        }

        private void button2_Click(object sender, EventArgs e)
        {
            myCount++;
            MessageBox.Show("myCount = " + myCount.ToString());
            //Insert Record Into  SQL File
            mySqlCmd.Connection = myDB;
            mySqlCmd.CommandText = "INSERT INTO Parent(ParentName) Values(myCount)";
            myDA = new SqlDataAdapter(mySqlCmd);
            mySqlCmd.ExecuteNonQuery();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Read Record From SQL File
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //Read All Records From SQL File
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //Delete Record From DQL File
        }

        private void button6_Click(object sender, EventArgs e)
        {
            MessageBox.Show("myDB state = " + myDB.State.ToString());
            //Close SQL File
            myDB.Close();
            MessageBox.Show("myDB state = " + myDB.State.ToString());
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //Quit
            this.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 6

最可能的选择:

  1. 您程序的先前(崩溃)实例
  2. Visual Studio(表设计器打开或类似)

您可以通过查看Server Explorer来检查1)与TaskManager和2).您的数据库应显示一个小红叉,表示"已关闭".

您应该尽快重写代码以关闭连接.使用try/finally或using(){ }块.