Adapt beginner C# SQL Server INSERT example to work with my database

Posted by Mike Bertelsen on Stack Overflow See other posts from Stack Overflow or by Mike Bertelsen
Published on 2011-11-22T09:16:43Z Indexed on 2011/11/22 9:53 UTC
Read the original article Hit count: 496

Filed under:
|
|

I have read TONS of tutorials, articles and whatever regarding my issue and honestly, due to my lack of experience I can't twist my fingers around this one so I hope some of you guys can help me out :)

I am working on a project (simply to learn how to program so it's probably very basic), but I have this "News" page where I can update and delete data using a GridView.

Now I would like to INSERT something into my database using 3 textboxes and 1 submit button.

I have 3 rows that has to be inserted:

  1. Headline
  2. Date
  3. Content/the news itself.

Which are stored under NyhedTB from the connectionstring: BoligStjernenConnectionString

My query looks like this:

INSERT INTO [NyhedTB] ([NyhedDato], [NyhedTitel], [NyhedTekst])
VALUES (@NyhedDato, @NyhedTitel, @NyhedTekst)

I read on the internet that this code should do the magic for me (I will have to insert my own values ofc.):

static void Insert()
{
    try
    {
        string connectionString =
            "server=.;" +
            "initial catalog=employee;" +
            "user id=sa;" +
            "password=sa123";
        using (SqlConnection conn =
            new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd =
                new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
                    "@Id, @Name, @Address)", conn))
            {
                cmd.Parameters.AddWithValue("@Id", 1);
                cmd.Parameters.AddWithValue("@Name", "Amal Hashim");
                cmd.Parameters.AddWithValue("@Address", "Bangalore");

                int rows = cmd.ExecuteNonQuery();

                //rows number of record got inserted
            }
        }
    }
    catch (SqlException ex)
    {
        //Log exception
        //Display Error message
    }
}

I looked at this code and thought it should be easy enough but really, I can't figure it out.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET