Donate

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

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.