Arsalan Saleem
Arsalan Saleem

Reputation: 361

How to save data to Database

I have searched and found out this code to save data to database, connection string is ok, and no exceptions/errors are thrown, but i dont know why this code is not saving data into my database..

    string query = "Insert Into BookConfiguration (BookNum, x_axis, y_axis, BookName) Values (@BookNum, @x_axis, @y_axis, @BookName)";
    string connStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\BookShelf.mdf;Integrated Security=True;User Instance=True";


    try
    {
        using (SqlConnection conn = new SqlConnection(connStr))
        {                   
                SqlDataAdapter da = new SqlDataAdapter();
                da.InsertCommand = new SqlCommand(query, conn);
                da.InsertCommand.Parameters.Add("@BookNum", SqlDbType.Int).Value = quantity;
                da.InsertCommand.Parameters.Add("@x_axis", SqlDbType.Int).Value = x;
                da.InsertCommand.Parameters.Add("@y_axis", SqlDbType.Int).Value = y;
                da.InsertCommand.Parameters.Add("@BookName", SqlDbType.Text).Value = openFileDialog1.FileName;
            conn.Open();    

            da.InsertCommand.ExecuteNonQuery();

            conn.Close();
        }
    }

    catch (SqlException ex)
    {
        MessageBox.Show("Error Occured " + ex.Message);
    }

EDIT i have now changed the code same problem

code:

        try
        {
            using (TransactionScope scope = new TransactionScope())
            {

                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    {
                        cmd.Parameters.Add(new SqlParameter("@BookNum", quantity));
                        cmd.Parameters.Add(new SqlParameter("@x_axis", x));
                        cmd.Parameters.Add(new SqlParameter("@y_axis", y));
                        cmd.Parameters.Add(new SqlParameter("@BookName", openFileDialog1.FileName));
                        cmd.ExecuteNonQuery();
                    }
                    conn.Close();
        }

                scope.Complete();
            }
        }

i hope it is clear not vague...

coded in c# visual studio 2010 sql server 2008...

Upvotes: 1

Views: 22139

Answers (1)

Aaron Bertrand
Aaron Bertrand

Reputation: 280252

I can almost guarantee that because you are using the deprecated User Instances / AttachDbFileName features, that you are looking at a different copy of your database than your program is.

Please see the answer from @marc_s here for how to proceed:

https://stackoverflow.com/a/10740026/61305

Essentially, stop using this useless feature. Attach your database to a real instance of SQL Server, then your database is fixed, and you can connect to the same copy of it as your program...

Upvotes: 4

Related Questions