CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2011
    Posts
    1

    Connecting to data base in visual studio.Net

    Hi guys,
    I connected to database using the following code
    SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DBDB.mdf;Integrated Security=True;User Instance=True");
    SqlCommand cmd = cn.CreateCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "StoredProcedure";
    SqlParameter par = cmd.Parameters.Add("@GlobalNumberID", SqlDbType.BigInt);
    par.Direction = ParameterDirection.Input;
    par.Value = Convert.ToInt64(textBox1.Text);
    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();

    Stored procedure is
    ALTER PROCEDURE StoredProcedure1

    (
    @GNumber BigInt
    )

    AS
    Insert into NumberTable(GNumber)
    Values (@GNumber)
    RETURN

    there is no error but when I check the table there is no data added to it WHY?
    I really give up is the problem with my bconnection or what?
    Can ANY one help me

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Connecting to data base in visual studio.Net

    I'm surprised there isn't any errors because you specified the wrong stored procedure name and variable name.

    In the code you have "StoredProcedure" and "@GlobalNumberID".

    Yet, the storeprocedure is defined as:
    Code:
    ALTER PROCEDURE StoredProcedure1
    (
     @GNumber BigInt
    )
    Also, 'using' blocks help with immediately cleaning up resources (which is very important when working with databases).

    Rewriting the code to use using blocks looks like:
    Code:
    using( var cn = new SqlConnection( ... ) )
    {
      using( var cmd = cn.CreateCommand() )
      {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "StoredProcedure1";
        cmd.Parameters.AddWithValue( "@GNumber ", Convert.ToInt64(textBox1.Text) );
        cn.Open();
        cmd.ExecuteNonQuery();
      }
    }
    The using blocks free up the SqlConnection and SqlCommand objects right at the closing braces.

    You might also notice I've called AddWithValue for the sproc variable. This method is smart enough to realize the value is an Int64.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured