Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

inserire più record con un solo clic sul pulsante in modo dinamico

Se non conosci il no esatto dei soggetti da inserire nei voti, come dovremmo generare una query per farlo?

Tuttavia, per mostrarti come proteggerti dagli attacchi SQL Injection, hai inserito SQL in 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

Quindi nel codice chiamiamo la stored procedure, notiamo i Parameterized Commands, questo previene gli attacchi di SQL Injection. Ad esempio, supponiamo di aver digitato nella casella di testo/ddl del semestre (o utilizzando FireBug per modificare il valore degli elementi) 1 UNION SELECT * FROM Master.Users - l'esecuzione di questo SQL ad hoc potrebbe restituire l'elenco degli account utente SQL ma è passato un comando parametrizzato evita il problema:

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;
}