使用存储过程的优点.
Why use Store procedure
?
第一:提高性能
第二:減少網(wǎng)絡流量
第三:減少注入式攻擊
3.1易受注入式攻擊的代碼:
3.2優(yōu)化過的代碼
3.3使用存儲過程來減少注入攻擊
?
?
?
第一:提高性能
當存儲過程被創(chuàng)建,它要經(jīng)過以下幾步,第一步,它所包含的T-SQL語句將被分析和解析,并被存儲.當?shù)谝淮伪粓?zhí)行時,它將被調(diào)出并被優(yōu)化.SQLServer會根據(jù)statistics自動選擇相應的優(yōu)化策略.
此后查詢計劃將被存儲在高速緩存中,以利于將來使用.由于不用被重新編譯,所以可以大大提高效率.
?
第二:減少網(wǎng)絡流量
你可能使用T-SQL語句來對表執(zhí)行插入操作.但是如果我們創(chuàng)建一個存儲過程來進行這樣操作的話,每次插入的時候只要傳輸存儲過程名,參數(shù)和這些參數(shù)的數(shù)值,當這些操作非常頻繁時我們將會發(fā)現(xiàn)使用存儲過程可以減少額外的網(wǎng)絡傳輸.這在我們使用Internet時進行傳輸時非常有用.
比較以下兩個語句:
?? INSERT INTO EmployeeTerritories (EmployeeID, TerritoryID)? ?VALUES (3,12345)?
??Ins_EmployeeTerritories @empId=3,@terrId=12345What if an image data type was being uploaded or downloaded?
?Anything that is of binary data type, such as images or sounds, and so on, is sent as binary values. These are converted to character strings, and this will double the size of the ad-hoc query that we are sending, when using T-SQL inline.
第一個語句有74個字符,第二個有46個字符,相比而言網(wǎng)絡傳輸量減少了37.84%,如果我們這個插入語句中包括有更多要插入數(shù)據(jù)的列,并且每天被執(zhí)行10,000次,將會學雜費280K左右的帶寬,
?
第三:減少注入式攻擊
?
3.1易受注入式攻擊的代碼:
?
// DANGER! User input used to generate database query
?
string sql = String.Format ("select count (*) " +
??? "from users where username=\'{0}\' and cast " +
??? "(password as varbinary)=cast (\'{1}\' as " +
??? varbinary)", username, password);
?
SqlCommand command = new SqlCommand (sql, connection);
int count = (int) command.ExecuteScalar ();
?
3.2優(yōu)化過的代碼
下面的代碼被注入式攻擊的機率要少些
?
// BETTER: Input passed to parameterized command
?
SqlCommand command = new SqlCommand
??? ("select count (*) from users where " +
??? "username=@username and cast (password as " +
??? "varbinary)=cast (@password as varbinary)",
???? connection);
?
command.Parameters.Add ("@username", SqlDbType.VarChar).Value = username;
command.Parameters.Add ("@password", SqlDbType.VarChar).Value = password;
int count = (int) command.ExecuteScalar ();
?
?
3.3使用存儲過程來減少注入攻擊
通過存儲過程來執(zhí)行效果會更好
?
// BEST: Input passed to stored procedure
?
SqlCommand command = new SqlCommand ("proc_IsUserValid", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add ("@username", SqlDbType.VarChar).Value = username;
command.Parameters.Add ("@password", SqlDbType.VarChar).Value = password;
command.Parameters.Add ("@return", SqlDbType.Int).Direction =
??? ParameterDirection.ReturnValue;
int count = (int) command.ExecuteScalar ();
?
所以我們應該盡量在我們的應用系統(tǒng)中使用存儲過程.
轉(zhuǎn)載于:https://www.cnblogs.com/net2004/archive/2005/04/14/137605.html
總結(jié)
以上是生活随笔為你收集整理的使用存储过程的优点.的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Addin and Automation
- 下一篇: 很多网站,软件对自定义的dpi支持不好