Hvis du ikke kender det nøjagtige antal emner, der skal indtastes - hvordan skal vi generere en forespørgsel for at gøre det?
Ikke desto mindre for at vise dig for at beskytte dig mod SQL Injection-angreb, sætter du din SQL i Stored Procs:
create PROCEDURE [dbo].[pr_GetAssignedSubjectsByFacultyIdAndSemester]
@FacultyID int,
@Semester nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
SELECT [Faculty], [Subjects],[CreatedBy],[CreatedDate],[ModifiedBy],[ModifiedDate]
FROM [dbo].[tblNotSure]
WHERE [FacultyID] = @FacultyID
AND [Semester] = @Semester
AND [IsDeleted] = 0
END
Så i kode kalder vi den lagrede procedure, læg mærke til de parametriserede kommandoer, dette forhindrer SQL Injection-angreb. Lad os for eksempel sige, at vi har indtastet semesteret ddl/textbox (eller brugt FireBug til at redigere elementernes værdi) 1 UNION SELECT * FROM Master.Users - udførelse af denne ad-hoc SQL kunne returnere listen over SQL-brugerkonti, men bestået gennem en parameteriseret kommando undgår problemet:
public static aClassCollection GetAssignedSubjectsByFacultyIdAndSemester(int facultyId, string semester)
{
var newClassCollection = new aClassCollection();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString))
{
using (var command = new SqlCommand("pr_GetAssignedSubjectsByFacultyIdAndSemester", connection))
{
try
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@facultyId", facultyId);
command.Parameters.AddWithValue("@semester", semester);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
newClassCollection.Add(new Class(){vals = dr["vals"].ToString()});
}
}
catch (SqlException sqlEx)
{
//at the very least log the error
}
finally
{
//This isn't needed as we're using the USING statement which is deterministic finalisation, but I put it here (in this answer) to explain the Using...
connection.Close();
}
}
}
return newClassCollection;
}