Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Should we escape ' when building command text?
Message
 
 
À
03/01/2008 12:44:00
John Baird
Coatesville, Pennsylvanie, États-Unis
Information générale
Forum:
ASP.NET
Catégorie:
Bases de données
Versions des environnements
Environment:
ASP.NET
OS:
Windows XP
Database:
MS SQL Server
Divers
Thread ID:
01278630
Message ID:
01279297
Vues:
16
>>>Yes, parameters are *definitely* better and yes, you won't need to worry about escaping the quote.
>>>
>>>
>>>Command.CommandText = "INSERT INTO Programs (ProgName, ProgramDescription, " +
>>>                "Location, CoordinatorID) VALUES(@Name, @Description, @Location, @ID)\nSELECT @@IDENTITY";
>>>Command.Parameters.AddWithValue("@Name", this.txtbName.Text);
>>>Command.Parameters.AddWithValue("@Description", this.txtbDescription.Text);
>>>Command.Parameters.AddWithValue("@Location", this.txtbLocation.Text);
>>>Command.Parameters.AddWithValue("@ID", CoID);
>>>
>>>
>>
>>Hi Bonnie,
>>
>>Can I use the same technique within a loop or I should go John's way?
>>
>>I tried to change the original code using string.Format to
>>
>>            foreach (ListItem Item in this.lsbEvntTargetPop.Items)
>>            {
>>                if (Item.Selected)
>>                {
>>                    Command.CommandText += "\nINSERT INTO EventTargets VALUES(@EvID,@EventVal)";
>>                    Command.Parameters.AddWithValue("@EventVal", Item.Value);
>>
>>                }
>>            }
>>
>>but I'm getting an error. How should I change this?
>>
>>Thanks again for your help.
>
>
>Naomi,
>
>In your example, you are appending the insert command to the command text over and over and over. It will error on that alone.
>If you want to add separate insert statements you must use a ';' to end the statement before you append the next.

No, this part works fine. This is the original working code which I tried to "improve" (see the commented lines):
 Command.CommandText += "SET @EvID = @@IDENTITY";
            foreach (ListItem Item in this.lsbEvntTargetPop.Items)
            {
                if (Item.Selected)
                {
                    //Command.CommandText += "\nINSERT INTO EventTargets VALUES(@EvID,@EventVal)";
                    //Command.Parameters.AddWithValue("@EventVal", Item.Value);
                    Command.CommandText += string.Format("\nINSERT INTO EventTargets VALUES(@EvID,'{0}')", Item.Value);

                }
            }
If it's not broken, fix it until it is.


My Blog
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform