Insert Multiple Records In One Connection

I want to update a contactInfo database using C#. I need to insert (possibly) multiple people/emergency contacts from a windows form. So I am setting the textboxes on the windows form equal to variables to pass into my query. I know how to do one record per connection, but how would I do two? so for example if a secondary emergency contact was supplied how could I also insert the data provided in txt2fname, txt2lname, txt2phone1, txt2phone2?

SqlConnection con = new SqlConnection("ConnectionStringGoesHere")
{
SqlCommand cmd;
try
{
  string emergencyContactInfo = "Insert Into econtactInfo(fname, lname, phone1, phone2) Values(@fname, @lname, @phone1, @phone2)";
  cmd = new SqlCommand(emergencyContactInfo, con);
  con.Open();
  cmd.Parameters.AddWithValue("@fname", txt1fname);
  cmd.Parameters.AddWithvalue("@lname", txt1lname);
  cmd.Parameters.AddWithValue("@phone1", txt1phone1);
  cmd.Parameters.AddWithvalue("@phone2", txt1phone2);
  cmd.ExecuteNonQuery();
  connection.Close()
}
}

Upvotes: 0

Views: 288

Answers (2)

Sam
Sam

Reputation: 789

Try this :

string SqlString =@"Insert into mytable(f1,f2) values ('1','2'),
Insert into mytable(f1,f2) values ('3','4'),
Insert into mytable(f1,f2) values ('5','6'), ";
con.Execute(SqlString);

Or something like this

       SqlConnection con = new SqlConnection("ConnectionStringGoesHere")
        string emergencyContactInfo = @"Insert Into econtactInfo(fname, lname, phone1, phone2) Values({0}, {1}, {2}, {3})";
        con.Open();
for(....)
{
        con.Execute(String.Format(emergencyContactInfo ,txt1fname,txt1lname,txt1phone1 txt1phone2));
}
        connection.Close();

Upvotes: 0

fabricio
fabricio

Reputation: 1393

You just need to go something like this..

string emergencyContactInfo = "Insert Into econtactInfo(fname, lname, phone1, phone2)     Values(@fname, @lname, @phone1, @phone2)";
cmd = new SqlCommand(emergencyContactInfo, con);
con.Open();

cmd.Parameters.Add("@fname", SqlDbType.<Type>);
<Add the other parameters here>
...

cmd.Parameters["@fname"].Value = txt1fname
<Add parameters values here>
...
cmd.ExecuteNonQuery();

cmd.Parameters["@fname"].Value = txt2fname
<Add parameters values here>
...
cmd.ExecuteNonQuery();

connection.Close()

Upvotes: 1

Related Questions