0
String ConString =  @"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BizContact.mdf;Integrated Security=True;User Instance=True";

SqlConnection cn = new SqlConnection(ConString);
try
{
   cn.Open();
   MessageBox.Show("connect");
}
catch (Exception)
{
   MessageBox.Show("Did not connect");
}       

SqlCommand cmd = new SqlCommand("insert tableNote values (@UserName,@Note)",cn);
cmd.Parameters.AddWithValue("@UserName", textBox1.Text);
cmd.Parameters.AddWithValue("@Note", textBox2.Text);

try
{
   int res = cmd.ExecuteNonQuery();

   if (res > 0)
   {
      MessageBox.Show("insert");
   }
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message);
}
finally
{
   cn.Close();
}

I am trying to add new row to the database. The above code is correct with no error and it display the try statement but does not insert row into the database. Any idea to solve it.

3
  • try printing value of res. It should be 1 because it gives the number of rows inserted. Commented Apr 29, 2012 at 7:10
  • Look in your project directory, there may be multiple copies of BizContact.mdf Check all of them for your inserted record. Commented Apr 29, 2012 at 7:15
  • Try to use SQL Profiler and see the query generated and try to run it in SSMS . Commented Apr 29, 2012 at 7:19

3 Answers 3

4

try full T-SQL statement

"INSERT INTO table_name (userColumn, noteColumn) VALUES (@UserName, @Note)"

also dispose SqlConnection via using state

using(SqlConnection  cn = new SqlConnection(ConString))
{
  //....
}
Sign up to request clarification or add additional context in comments.

Comments

3

Your insert statement is wrong (missing into). Do either:

insert into tableNote select @UserName,@Note

or

insert into tableNote (column_name1, column_name2) values (@UserName,@Note)

Comments

0

Open up Sql Profiler and watch it execute the command, then try replaying that command into Sql Management Studio. More than likely, it'll show you that the query is ever so slightly malformed such that it happily does nothing successfully.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.