-3

I have a table of 3 columns along with a primary key:

create table tempTable
(
    id int primary key identity,
    name nvarchar(50),
    gender nvarchar(50),
    city nvarchar(50)
)

And there is a list of string like this:

List<String> list = new List<String>() { "name", "male", "city" };

I want this list into the tempTable. How can I do that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Safayat Zisan
  • 33
  • 1
  • 13
  • 1
    Your question is both unclear and shows no effort. Is the temp table ***really*** a temp table? Are you using raw ADO.Net? What have you tried so far? – David L Aug 14 '16 at 19:26
  • 2
    there are a lot of ways to do it, what have you tired? here is a link that shows you 1 way to insert the data into a table http://stackoverflow.com/questions/14001040/inserting-new-row-in-sql-database-table with that and a for each loop on your list you can accomplish it. There are enve more ways too. – Matt Aug 14 '16 at 19:27
  • the name of the table is tempTable I am using raw ado.net here is my code so far. But I know, it is not making any sense. List list = new List() { "A", "B", "C" }; string qry = "INSERT INTO tempTable VALUES(@Column)"; using (var cmd = new SqlCommand(qry, connection)) { cmd.Parameters.Add("@Column", SqlDbType.VarChar); foreach (var value in list) { cmd.Parameters["@Column"].Value = value; cmd.ExecuteNonQuery(); } } – Safayat Zisan Aug 14 '16 at 19:28
  • 1
    @SafayatZisan - instead of adding it as a comment edit your question and add it there – Gilad Green Aug 14 '16 at 19:30

1 Answers1

1

You should do something like this:

string query="INSERT INTO tempTable(name, gender, city) VALUES (@name, @gender, @city)";
using (var connection = new SqlConnection(connectionString))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;
        command.CommandString = query;
        command.CommandType = CommandType.Text;
        command.Parameters.AddWithValue("@name", list[0]);
        command.Parameters.AddWithValue("@gender", list[1]);
        command.Parameters.AddWithValue("@city", list[2]);
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            // your code...
        }
    }
}
Sleepy Panda
  • 458
  • 3
  • 9
  • 1
    You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results... – marc_s Aug 14 '16 at 20:52
  • Wow! I never had issues with AddWithValue(). But I think that's very interesting link. Thank you :) – Sleepy Panda Aug 14 '16 at 20:58