Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
OK, after working on my code regarding my original question (below in italics), I think I have a (slightly !) better understanding of how this works and I think I have better code ... however, it is still not working & I am confused !!!

I have amended my code to use the "USING" statement as I am led to believe from what I have read that it will release resources when I have finished with them, even if their is a program failure, but it doesn't seem to be doing that for me ...

Here is the timeline leading to my problem :

1) Open the Project within VS2010
2) Add a new Item / Data / Service Based Database / DataSet & then create a single Table, so the Database is called MyTestDB, the Table is MyTestTbl, & the fields are MyTestID (Int, Primary Key, IsIdentity True, 1,1) & MyTestNum (Int)
3) Build Succeeded
4) Run the Program in Debug mode, Form displays, Click on Insert
5) MyCount = 1, MessageBox says myDB.State = Open, process data, MessageBox says myDB.State =Closed, Form re-displays.
6) Repeat, repeat, repeat, etc. ... MyCount progresses as expected, no problems, Quit & program ends.
7) Now we have a problem ... Firstly, there are still no records in the database !!! If I right-click on the MyTestTbl Table in Server Explorer and "Show Table Data" it just shows the Headings & Null, Null. Question 1 : Why ? Do I have to add another line of code to "commit" the update or something ?!?
8) If I now run the Program in Debug mode again, it will not run because I have 2 Errors, similar to my original problem, something to do with files in the \bin\debug Folder already existing ... "Unable to copy file <path> \MyTestDB.mdf to bin\Debug\MyTestDB.mdf. The process cannot access the file bin\Debug\MyTestDB.mdf because it is being used by another process. (the same error message for the file MyTestDB_log.ldf). Question 2 : Again, why ?!? Why are these files getting locked, or blocked ?!?

This is my code, surely it shouldn't be this difficult !!!

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MySqlTest
{
    public partial class Form1 : Form
    {
        int myCount;
        string myDBlocation = @"Data Source=MEDESKTOP;AttachDbFilename=|DataDirectory|\MyTestDB.mdf;Integrated Security=True;User Instance=False";

        public Form1()
        {
            InitializeComponent();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            myCount++;
            MessageBox.Show("myCount = " + myCount.ToString());
            //Insert Record Into  SQL File
            myDB_Insert();
        }

        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 SQL File
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //Quit
            myDB_Close();
            this.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Close(object sender, EventArgs e)
        {

        }

        void myDB_Insert()
        {
            using (SqlConnection myDB = new SqlConnection(myDBlocation))
            using (SqlCommand mySqlCmd = myDB.CreateCommand())
            {
                myDB.Open();
                MessageBox.Show("State = " + myDB.State);
                mySqlCmd.CommandText = "INSERT INTO MyTestTbl(MyTestNum) VALUES(@MyTestNumValue)";
                mySqlCmd.Parameters.AddWithValue("@MyTestNumValue", myCount);
                mySqlCmd.ExecuteNonQuery();
                myDB.Close();
                MessageBox.Show("State = " + myDB.State);
            }
            return;
        }

        void myDB_Close()
        {
            using (SqlConnection myDB = new SqlConnection(myDBlocation))
            using (SqlCommand mySqlCmd = new SqlCommand())
            {
                myDB.Close();
            }
            return;
        }

    }
}


I have written a very small C# program, that uses a very small SQL Server database, purely for some learning & testing purposes. The database is used in this one new project and nowhere else. However, I am getting problems whilst running Debugs where the program will not run, because the database "is being used by another process".

If I reboot my machine, it will work again, and then after a few test runs I will get the same problem again.

I have found many, many similar problems reported all over the Internet, but can find no definitive answer as to how to resolve this problem. Firstly, how do I find out what "other process" is using my .mdf & .ldf files ? Then, how do I get these files released & not held in order to stop this happening time after time after time ?!?

I am new to VS2010, SQL Server & C#, so please be quite descriptive in any replies you give me !!!

This is my code, as you can see, you couldn't get anything much more basic, I certainly shouldn't be running into these constant problems !!!


C#
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;

    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();
            }
        }
    }
[/code]
Posted
Updated 17-Sep-17 18:52pm
v3

The other process is almost certainly your program, what other program would be using it ? Why are you using Access style database files at all ? If you must use flat files, I recommend SQLite, which allows multiple connections. In any case, this[^] shell extension will allow you to find out who is locking your file, and release it.
 
Share this answer
 
Comments
Gary Heath 8-Feb-12 9:51am    
Sorry Christian, I don't understand ... what do you mean by "Access style database files" ? Everything I am doing here is created inside VS2010 & from C# & SQL Server sites I have found online. Where am I using "flat files" ?!?

Also, WhoLockMe is crashing, maybe it doesn't work in Vista :-( !!!
Christian Graus 8-Feb-12 9:53am    
When you have an mdb file, and when it's possible for another process to lock it, you're using a flat file. Yes, WhoLockMe stopped working at Vista, I think. Either way, use the process viewer, it has to be your program, I suspect if your program crashes, it probably leaves the DB in this state. Put a top level crash handler in your app that closes the DB.
Gary Heath 8-Feb-12 13:48pm    
@Christian, Can you please explain (or point me at an example) of what you mean by "Put a top level crash handler in your app that closes the DB." ...
Christian Graus 8-Feb-12 14:48pm    
If you put a try/catch block at the very top of your code, and expose your DB connection so that, in that, you make sure it is closed, that's the best you can do.
try to kill the process on SQL Server

see this link below

http://www.kodyaz.com/articles/kill-all-processes-of-a-database.aspx[^]


Accept or vote if this will help you
thanks
 
Share this answer
 
v2
I had to go into Services & find MSSQLSERVER, change the Start option to Manual, then physically Stop it ... than and only then, was I able to delete the files in the bin\debug folder !!! I altered the Start option back to Automatic & started the Service, and at last, it is all working again !!! Now I have to find out why it is happening and to prevent it from happening again ...
 
Share this answer
 
It certainly seems that VS2010 gets its knickers in a twist when you add a New Database within the Project and then use the Debug routine.

I have resolved this now by using a New Database that I created in MS SQL Server Management Studio and I added it to the VS2010 C# Project as an Existing Item, rather than a New Item, and it works just fine ... phew, at last !!!
 
Share this answer
 
CLSBasicFunctionality.objCreateDB.Con.Close();
           GC.Collect();
           GC.WaitForPendingFinalizers();




use gc.wait for pending finalizers after gc.collect
 
Share this answer
 
v2
Comments
Graeme_Grant 18-Sep-17 1:21am    
WHY are you answering a 5-YEAR-OLD question that has ALREADY ACCEPTED an answer. Please don't, instead focus on current question ONLY - there are always plenty waiting for help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900