Insert Parameter Array in .NET (C# Version)
The first version i created was a vb.net version. Here is the C# version:
myConn objCon = Program.connectionstring; string str = objCon(); //pass delegate to string SqlConnection connection = new SqlConnection(str); try { List<Patient>patients = new List<Patient>(); for(int i = 0; i < 5; i++) { Patient patient = new Patient(); patient.name = "greg" + i; patient.code = i*2; patients.Add(patient); } //insert into array connection.Open(); StringBuilder query = new StringBuilder(); SqlCommand cmd = new SqlCommand(); for (int j = 0; j < patients.Count; j++) { query.Append(string.Format("Insert into patients (PatientName,PatientSexCode) values (@names{0},@code{1});",j,j)); //declare the parameters cmd.Parameters.AddWithValue(String.Format ("@names{0}",j), patients[j].name); cmd.Parameters.AddWithValue(String.Format ("@code{0}",j), patients[j].code); } cmd.Connection = connection; cmd.CommandText = query.ToString(); cmd.ExecuteNonQuery(); } catch (Exception exception) { throw new Exception(exception.Message); } connection.Close(); Console.Write("Array successfully saved"); Console.ReadLine();
Comments
Post a Comment