通常我使用SQL参数来避免黑客注入SQL。但是如何在循环中使用SQL参数:
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
string sSql = "";
foreach (var oItem in LeListVoit_End)
{
//insert into Lettrvoit
if (sSql != "") sSql += " UNION ALL ";
sSql += "SELECT '" + oItem.IdLettre + "', '" + oItem.Date_Cloture + "', '" + oItem.CodeDest + "', '" + oItem.ModalMode + "', '" + oItem.LibPort + "', '" + oItem.LibExpr + "', '" + oItem.LibUnite + "', '" + oItem.EnlvUnite + "', '" + oItem.NbrColis + "', '" + oItem.Poids.ToString().Replace(',', '.') + "', '" + oItem.LeCR.ToString().Replace(',', '.') + "', '" + oItem.LeVD.ToString().Replace(',', '.') + "', '" + oItem.CodeClient + "', '"
+ oItem.RsNom_Exp + "', '" + oItem.Addr_Exp + "', '" + oItem.CP_Exp + "', '" + oItem.Ville_Exp + "', '" + oItem.Tel_Exp + "', '" + oItem.Fax_Exp + "', '"
+ oItem.RsNom_Dest + "', '" + oItem.Addr_Dest + "', '" + oItem.CP_Dest + "', '" + oItem.CP_Dest + "', '" + oItem.Tel_Dest + "', '" + oItem.Fax_Dest + "', '" + oItem.InseeDest + "', '"
+ Is_Print + "', '" + CHAUFFEUR + "'";
}
string sqlComm_Insert = "INSERT INTO LETTRE_VOIT_FINAL ([NOID], [DATE_CLOTURE], [CODE_DEST] ,[MODAL_MODE], [LIBELLE_PORT] ,[LIBELLE_EXPR], [LIBELLE_UNITE],ENLEV_UNITE, [NBR_COLIS], [POID], [ENLEV_CREMB], [ENLEV_DECL], CODE_CLIENT, [RS_NOM_EXP] ,[ADDR_EXP] ,[CP_EXP] ,[VILLE_EXP] ,[TEL_EXP] ,[FAX_EXP],[RS_NOM_DEST] ,[ADDR_DEST] ,[CP_DEST] ,[VILLE_DEST] ,[TEL_DEST] ,[FAX_DEST],INSEE_DEST, IS_PRINT, CHAUFFEUR) " + sSql;
SqlCommand comm_Insert = new SqlCommand(sqlComm_Insert, connectionWrapper.conn);
comm_Insert.ExecuteScalar();
}
}
catch (Exception excThrown)
{
throw new Exception("Err", excThrown);
}
如上所示,SQL参数不在我的循环中。
答案 0 :(得分:2)
由于SQL参数名称必须是唯一的,因此您可以使用for循环,并在每次迭代中将循环变量的索引附加到SQL参数名称,即:
for(int i=0; i< LeListVoit_End.Length; i++)
{
string sql = string.Format("select foo from bar where baz = @FOO{0}" i);
command.Parameters.Add(string.Format("@FOO{0}",i), SqlDbType.VarChar, 80).Value = "someValue";
}
答案 1 :(得分:0)
您可以编写存储过程而不是构建语句字符串吗?无论哪种方式,我都会在列表中的每个项目上执行命令,并在单个事务中执行所有命令。
使用Parameters集合添加参数:
command.Parameters.Add({several overloads})
答案 2 :(得分:0)
您可以在循环外创建连接,命令和参数,然后只需设置参数值并在循环中执行命令:
comm_Insert.Parameters[""].Value = "";
comm_Insert.ExecuteScalar();