简体   繁体   中英

Insert data into SQL Server from a C# / ASP.NET application

This is my first time writing a database insert.

Working on my own and following other people examples I was able to write this code below.

using (SqlConnection openCon = new SqlConnection(""))
{
    String connection = "INSERT INTO Damage (Area,Building,Conference,Apartment,Room,DescribeDamage) VALUES (@Area,@Building,@Conference,@Apartment,@Room,@DescribeDamage)";
    using (SqlCommand CCC = new SqlCommand(connection, openCon))
    {
        try
        {
            openCon.Open();
            CCC.Connection = openCon;
            CCC.CommandType = CommandType.Text;
            CCC.Parameters.Add("@Area", SqlDbType.Char, 24).Value = MainDDL.SelectedItem.ToString();
            CCC.Parameters.Add("@Building", SqlDbType.Char, 9).Value = ddlBuildingCCC.SelectedItem.ToString();
            CCC.Parameters.Add("@Conference", SqlDbType.Char, 5).Value = txtConferenceCCC.ToString();
            CCC.Parameters.Add("@Apartment", SqlDbType.VarChar, 4).Value = txtApartmentCCC.ToString();
            CCC.Parameters.Add("@Room", SqlDbType.VarChar, 10).Value = txtRoomCCC.ToString();
            CCC.Parameters.Add("@DescribeDamage", SqlDbType.VarChar, 100).Value = txtDescribeCCC.ToString();
            CCC.ExecuteNonQuery();
            CCC.Dispose();
        }
        catch (SqlException)
        {
            // error here
        }
        finally
        {
            openCon.Close();
        }
    }
}

Updated code from Guffa below, i am going to rewrite according to your comments but i want to see if i can get this to work first.

using (SqlConnection connection = new SqlConnection("Asset managementConnectionString"))
    {
        String query = "INSERT INTO Damage (Area,Building,Conference,Apartment,Room,DescribeDamage) VALUES (@Area,@Building,@Conference,@Apartment,@Room,@DescribeDamage)";
        using (SqlCommand CCC = new SqlCommand(query, connection))
        {
            try
            {
                connection.Open();
                CCC.CommandType = CommandType.Text;

                CCC.Parameters.Add("@Area", SqlDbType.Char, 24).Value = MainDDL.SelectedItem.ToString();
                CCC.Parameters.Add("@Building", SqlDbType.Char, 9).Value = ddlBuildingCCC.SelectedItem.ToString();
                CCC.Parameters.Add("@Conference", SqlDbType.Char, 5).Value = txtConferenceCCC.ToString();
                CCC.Parameters.Add("@Apartment", SqlDbType.VarChar, 4).Value = txtApartmentCCC.ToString();
                CCC.Parameters.Add("@Room", SqlDbType.VarChar, 10).Value = txtRoomCCC.ToString();
                CCC.Parameters.Add("@DescribeDamage", SqlDbType.VarChar, 100).Value = txtDescribeCCC.ToString();
                CCC.ExecuteNonQuery();
            }
            catch (SqlException)
            {
                throw; // just rethrow for now
            }
        }
    }


        Response.Redirect("~/Default.aspx");
    }
}

I lost the first example i was following along with and haven't been able to find it again. So I think i am trying two combine two different methods by accident.

Problem : Right now nothing is debugging but i haven't had anything insert into the database. I think some of the code isn't needed, can you help me compact the code and getting the data inserting? I am to the point of rewriting the whole thing again following a different example. But i would like to know why this isn't working for experience.

UPDATED Problem , Figured out why me error where not getting reported even when i was throwing them. Right now i am getting

Format of the initialization string does not conform to specification starting at index 0. on using (SqlConnection connection = new SqlConnection("AssetmanagementConnectionString"))

I haven't been able to figure out the issue. What are the steps i can take to figure this out?

1. Don't swallow exceptions

Your code doesn't show any errors because you explicitly swallow any exceptions of type SqlException . Remove your catch segment or do something meaningful with the exception information.

2. Name variables properly

Naming a variable CCC is wrong for a lot of reasons. First, what it represents is unclear and second, in .NET world uppercase suggests a reference to a class member name. Use something like insertCommand instead.

3. Don't dispose an object that's declared in a using block.

Once the using block is over the variable will be disposed automatically.

4. Make sure your connection string isn't a literal, hard-coded string value.

If you ever need to switch db servers you'll want your connection string at one place so that only one change will be necessary. You can even make it a setting so that no recompiling will be necessary.

5. Avoid tight coupling

From the look of it you seem to set your parameter values directly off some UI controls. Don't do that. Instead encapsulate your inserting logic in a class that is independant of the UI, so that it will be easier to reuse it in the future.

That's about everything I can think of right off my head.

First of all, you won't need the line CCC.Dispose() because that's the point of the using block - the resource will be disposed after use.

The code looks pretty much OK, apart from this line:

CCC.Parameters.Add("@Area", SqlDbType.Char, 80).Value =  80;

If you are using a char type and giving it an integer value, an exception will occur. Since you are swallowing the exception you will not see this error at all hence why no data is inserted.

Change the code to be like below and see if that works:

CCC.Parameters.Add("@Area", SqlDbType.Char, 80).Value =  "80";

Unless your 'Area' field is actually an integer type in the database. In that case you should change the SqlDbType accordingly.

You are right that some code is not needed. But first:

  • Never catch an exception and just do nothing about it.

I suppose that you plan to put some error reporting there later, but in the mean time don't leave it as big hole where error messages goes to die. Just rethrow the exception so that you can see what's happening:

throw;

The try...catch block is of course only needed if you actually are going to catch the exception in this method. An alternative is to just omit the try...catch and let the exception bubble up and let code at a higher level handle it. It all depends on where you have enough information so that you can do something useful when you handle the exception.

The code that you don't need is:

  • As you set the connection when you create the SqlCommand object, you don't need to set it again.
  • As you are using using for both objects, you don't need to dispose the command or close the connection. THe using block does that for you.

Also:

  • Naming the query connection is just confusing. I renamed it query and used the connection name for the connection instead. (Using a better name for the command variable would also be advisable, but I left it as is in the code to leave it more like your original.)

Revised code:

using (SqlConnection connection = new SqlConnection("Asset managementConnectionString")) {
  String query = "INSERT INTO Damage (Area,Building,Conference,Apartment,Room,DescribeDamage) VALUES (@Area,@Building,@Conference,@Apartment,@Room,@DescribeDamage)";
  using (SqlCommand CCC = new SqlCommand(query, connection)) {
    try {
      connection.Open();
      CCC.CommandType = CommandType.Text;

      CCC.Parameters.Add("@Area", SqlDbType.Char, 80).Value =  80;
      CCC.Parameters.Add("@Building", SqlDbType.Char, 9).Value = ddlBuildingCCC.ToString();
      CCC.Parameters.Add("@Conference", SqlDbType.Char, 5).Value = txtConferenceCCC.ToString();
      CCC.Parameters.Add("@Apartment", SqlDbType.VarChar, 4).Value = txtApartmentCCC.ToString();
      CCC.Parameters.Add("@Room", SqlDbType.VarChar, 10).Value = txtRoomCCC.ToString();
      CCC.Parameters.Add("@DescribeDamage", SqlDbType.VarChar, 100).Value = txtDescribeCCC.ToString();
      CCC.ExecuteNonQuery();
    } catch (SqlException) {
      throw; // just rethrow for now
    }
  }
}

There may of couse still be error in the code, for example mismatching data types, but now you should get an error message about it.

Naming is one thing really important in coding. I was looking to your snippet and the first thing that got my eye is that your connection string, I would actually called it command.

var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

var command = "INSERT INTO Damage (Area,Building,Conference,Apartment,Room,DescribeDamage) VALUES (@Area,@Building,@Conference,@Apartment,@Room,@DescribeDamage)";

using (SqlConnection cnn = new SqlConnection(cnnString))
{
    using (SqlCommand cmd = new SqlCommand(command, cnn))
    {
        cmd.Parameters.AddWithValue("@Area", "80"); // Hardcoded value? Should be an int btw.
        cmd.Parameters.AddWithValue("@Building", ddlBuildingCCC.ToString());
        cmd.Parameters.AddWithValue("@Conference", ddlBuildingCCC.ToString());
        // ... the other values

        cnn.Open();
        cmd.ExecuteNonQuery();
    }
}

You also just need to open the connection before executing the command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM