.net – 提高SQL命令的代码可读性

前端之家收集整理的这篇文章主要介绍了.net – 提高SQL命令的代码可读性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我正在开发的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))

猜你在找的MsSQL相关文章