在我正在开发的Web应用程序的一个类中,我有一些相当长的SQL查询.
在开发三层应用程序时,使这种代码变得更好的最佳做法是什么?
Dim dc As New sqlCommand("INSERT INTO Choices VALUES ('" + _ SanitizeInput(strUser) + "','" + _ SanitizeInput(strFirstHalfDay) + "','" + _ SanitizeInput(strSecondHalfDay) + "','" + _ SanitizeInput(strFullDay) + "'," + _ SanitizeInput(Convert.ToInt32(firstHalfPaid).ToString()) + "," + _ SanitizeInput(Convert.ToInt32(secondHalfPaid).ToString()) + "," + _ SanitizeInput(Convert.ToInt32(fullPaid).ToString()) + ")",cn)
你认为这种代码是可以接受还是臭?
解决方法
停止,不要这样做,使用准备好的抱怨,你会得到安全和可读性.
改为使用它:
Dim dc As New sqlCommand("INSERT INTO Choices VALUES (@User,@FirstHalfDay,@SecondHalfDay,@FullDay,@FirstHalfPaid,@SecondHalfPaid,@FullPaid'",cn) dc.Parameters.Add (new sqlParameter ("User",strUser)) dc.Parameters.Add (new sqlParameter ("FirstHalfDay",strFirstHalfDay)) dc.Parameters.Add (new sqlParameter ("SecondHalfDay",strSecondHalfDay)) dc.Parameters.Add (new sqlParameter ("FullDay",strFullDay)) dc.Parameters.Add (new sqlParameter ("FirstHalfPaid",firstHalfPaid)) dc.Parameters.Add (new sqlParameter ("SecondHalfPaid",secondHalfPaid)) dc.Parameters.Add (new sqlParameter ("FullPaid",fullPaid))