简体   繁体   中英

Using C# to Insert lines from an array into SQL Server 2012

Earlier I posted this code but it was much more messy, parts were commented out, and I was using concatenation to INSERT to the database. I was told to clean it up, challenged to use parameters, and ask more concise questions. With that being said, the connection to the database was given to me with mostly pseudo-code with some direct commands.

1) Is my Try-Catch set up correctly?

2) "server = LOCALHOST" is underlined in red, it says it can't convert 'string' to System.Data.SqlClient.SqlConnection'

3) "Database" and "Lab1" are underlined saying it doesn't exist in current context? What does this mean?

4) "Trusted_connection" and "yes" have the same error message as #3.

5) I'm not sure what to put after "cmd.Connection = " which is why it's commented out and has a question mark after it.

6) Is my varname1.Close(); in the right spot? I feel like it makes sense for it to actually go between the last 2 closing brackets?

7) In the Catch "SqlException" is underlined and the error says "The type or namespace SqlException could not be found". I found a try-catch from another user on stackoverflow that asked the question and someone responded with the catch set up like that so I copied it.

8) I'm trying to figure out parameters, Is mine set up correctly? All I have is 1 textbox in which the user inputs data and it enters into an array. "Name" is the name of the attribute of the student in the database, and I just made up @Name as a variable? I found a parameter example from another user also on stackoverflow and kind of made match mine.

public static int counter = 0;
protected void btnDisplay_Click(object sender, EventArgs e)
{
    try
    {
        System.Data.SqlClient.SqlConnection varname1 = new System.Data.SqlClient.SqlConnection();
        varname1 = "server = LOCALHOST";
        Database = Lab1; 
        Trusted_connection = yes;
        varname1.Open();
        System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
       // cmd.Connection = (?)
        cmd.CommandText = "Delete From Student";
        cmd.ExecuteNonQuery();

     for(int i=0; counter >= i; i++)
     {
        cmd.CommandText = "INSERT INTO Lines (Name) " + "VALUES (@Name)";
        cmd.Parameters.AddWithValue("@Name", studentList[i]);
            counter++;
     }
    varname1.Close();
   }
    catch (SqlException ex)
    {
        lbl5.Text = "Connection could not be established";
    }
}

You need to find a good resource (or a few) and learn how to make proper database calls. Here's one. Here's another, on creating connection strings.

I haven't tested the following, but something like this should work.

using (var conn = new System.Data.SqlClient.SqlConnection("Server=LOCALHOSTDatabase=Lab1;Trusted_Connection=True;"))
{
    conn.Open();

    using (var cmd = new SqlCommand("Delete From Student", conn))
    {
        cmd.ExecuteNonQuery();
    }

    using (var cmd = new SqlCommand("INSERT INTO Lines (Name) VALUES (@Name)", conn))
    {
        for (int i = 0; counter >= i; i++)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@Name", studentList[i]);
            cmd.ExecuteNonQuery();
        }
        counter++;
    }
}

As for some of your other questions...

#1 - Your try/catch is setup okay.

#6 - Don't bother calling Close() - use a using block

#7 - The exception name looks okay. Do you have using System.Data.SqlClient; at the top of your form? You may be getting an error here because of other lines of code with errors... hard to say.

#8 - That looks fine.

  1. You should have a finally block with your try-catch
  2. Your SQLConnection should be created with the connection string as a parameter. You can't set it equal to a String, it's a SQLConnection.
  3. I don't know where Database and Lab1 are declared but it's obviously not within the scope of your function.
  4. See 3. And yes has no meaning.
  5. cmd.Connection = varName1
  6. You should close your connection in a finally block to ensure it is closed even if an exception is thrown
  7. Have you imported System.Data.SQLClient?
  8. Adding parameters with values will replace @Name in your SQL string with the value you supplied

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