Question

I'm working a WinForms based C# tool which has an attached MDF file based database. I'm trying to use the SqlCommand.ExecuteNonQuery() method to save a record to this attached MDF database, but the record is not saved. No error or exception occurs; only problem is that the record is not actually saved.

I have a Console.WriteLine at the top which shows the query I'm trying to run. Its correct syntax-wise, and if I copy-paste it from the output windows and run it separately, it works.

I have correctly defined the connection string as the following, and it works fine for fetching records:

public static String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestBuildDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

Here the function I'm using to save records:

public static void PerformDBWriteTransaction(string inputSQLStatement)
{
    Console.WriteLine(inputSQLStatement);
    DataTable returnDataTable = new DataTable();
    SqlConnection sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = connectionString;
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = sqlConnection;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = inputSQLStatement;
    cmd.Connection.Open();
    try
    {
        cmd.ExecuteNonQuery();
    }
    catch (SqlException ex)
    {
        errorMessages.Clear();
        errorMessages.Append("The following errors were found in the SQL statement:\n\n");

        for (int i = 0; i < ex.Errors.Count; i++)
        {
            errorMessages.Append("Index #" + i + "\n" +
                "Message: " + ex.Errors[i].Message + "\n" +
                "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                "Source: " + ex.Errors[i].Source + "\n" +
                "Procedure: " + ex.Errors[i].Procedure + "\n");
        }
        MessageBox.Show(errorMessages.ToString());
    }
    finally
    {
        cmd.Connection.Close();
    }
}

Can someone tell me what might be the problem ? Do I need to perform a 'commit' somehow ?

EDIT:

I have found the problem, and have written up a solution below .. Thanks to all who helped me out though :)

Was it helpful?

Solution

I found the problem ! It was very simple, and it was stupid really :) .. The code above is all correct .. Yes, people pointed out optimizations, etc, but still the code above was correct.

The problem was that when I imported the TestDB.MDF file into my Visual 2010 project, a copy of that was made inside the project's folder. When you run/debug the program, another copy of the this file is made and is put in the \bin\Debug\ folder. In the connection string I was using, I had mentioned: AttachDbFilename=|DataDirectory|\TestBuildDB.mdf .. This meant that all reads/writes were done to the copy in the bin\Debug folder. However, the TestDB.MDF file I was looking into to verify if records were inserted or not, was in the project's folder ! So basically, there were two MDF files, and I was writing the records into one file, but was trying to find them in the other :)

When you add an MDF file into your VS2010 Project, VS2010 by default makes a connection to that MDF file, from where you can browse the stuff in that MDF file .. The MDF file used for this purpose was the one placed in the project's folder, NOT the one in bin\Debug\ folder. And like I said earlier, my code used the one in the bin\Debug folder :)

So what I've done now is that I've removed the Test.MDF file reference from my project, which removes the copy present in the project's folder. However, I DO have a copy of TestDB.MDF file in the bin\Debug\ folder, which I connect to from within my application. And if I want to browse the MDf file outside my project, I use SQL Management Studio. The only problem here is that an MDF file can only be used by one program at a given time. So if I have to use it with my application, I have to take it offline from SQL Management studio, and vica versa !

I hope this explanation helps someone out there :)

OTHER TIPS

The solution to this problem is very simple just give the full path of the original MDF file in the connection String like this:

connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=**C:\VISUAL STUDIO 2012\PROJECTS\ENGLISHTOHINDIDICTIONARY\ENGLISHTOHINDIDICTIONARY\DICTIONARY.MDF**;Initial Catalog=Dictionary;Integrated Security=false"
        providerName="System.Data.SqlClient"

That's it, your problem is solved.

I had the same challenge, I simply changed the database property "Copy to Output Directory" from "Copy always" to "Do not copy" then moved my database.mdf (drag & drop from my IDE) into the bin\debug folder.

Tip: The bin directory is normally hidden, use the "Show All Files" to display it

Provide a catch clause for all Exceptions. If there something wrong other than SqlException, you will never see what is it and your db will neved be updated. Imagine there is a FormatException...

Also check the return of ExecuteNonQuery : it's the number of rows affected by the query.

First, you should always wrap up your IDisposable objects in a using to ensure they're closed and disposed of properly (and that connection pooling can do its thing). Second, when modifying data wrap up your sql in a transaction to maintain data integrity.

Try the following code and see if any exceptions are raised. I wouldn't normally recommend catching Exception as it's too general, I'd let that bubble up to the calling mechanism and handle it there - but for this instance it will show you any and all issues. I think your particular issue is at the .Open stage of the connection, so try stepping through.

public static void PerformDBWriteTransaction(string inputSQLStatement)
{
    DataTable returnDataTable = new DataTable();

    try
    {
        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();

            using (SqlTransaction sqlTrans = sqlConnection.BeginTransaction())
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand(inputSQLStatement, sqlConnection))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Transaction = sqlTrans;
                        cmd.ExecuteNonQuery();
                    }
                }
                catch (SqlException sqlEx)
                {
                    sqlTrans.Rollback();

                    throw sqlEx;
                }

                sqlTrans.Commit();
            }
        }
    }
    catch (Exception ex)
    {
        errorMessages.Clear();
        errorMessages.Append("The following errors were found in the SQL statement:\n\n");

        for (int i = 0; i < ex.Errors.Count; i++)
        {
            errorMessages.Append("Index #" + i + "\n" +
            "Message: " + ex.Errors[i].Message + "\n" +
            "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
            "Source: " + ex.Errors[i].Source + "\n" +
            "Procedure: " + ex.Errors[i].Procedure + "\n");
        }

        MessageBox.Show(errorMessages.ToString());
    }
}

Hi I am working on library database when I add student record executionNonQuery shows error like invalid column name page opens but saving data from not happening. Here I have given the code statement

public partial class add_student_info : Form
{
    SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-SPT6GLG\SQLEXPRESS;Initial Catalog=library_managment;Integrated Security=True;Pooling=False");

    public add_student_info()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into student_info values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "'," + textBox5.Text + "," + textBox6.Text + "," + textBox7.Text + ")";
            cmd.ExecuteNonQuery();
            con.Close();

            MessageBox.Show("Student recorc addedd sussfully");

        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top