2
Answers

not inserting values in sqldatabase

Ask a question
hello sir,
i am using this code to insert values in the book_info table in sqlserver database. i am using visual studio 2008.

private void btn_save_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS; AttachDbFileName=|DataDirectory|\library.mdf; Integrated Security=true; User Instance=true;");
            try
            {
                conn.Open();
                               
                SqlCommand cmd = new SqlCommand("INSERT INTO book_info (b_code) VALUES ('"+ txt_new_book_code.Text.Trim() +"') ", conn);

                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                conn.Close();
            }
            finally
            {
                conn.Close();
            }
        }
    }
when i click the save button first time (i think the entry gone in database) and when i click the save button again it gives primary key violation (b_code is primary key).
but when i stop my application and check the values in table nothing has been entered.
what is the problem.
please help me.
thanks in advance

Answers (2)