当前位置: 首页 > 图文教程 > 网络编程 > ASP > 怎么样写一段高效,安全的sql查询代码

ASP
ASP编程中15个非常有用的例子 (二)
ASP与JSP的比较(一)
ASP与JSP的比较(二)
ASP中五种连接数据库的方法
从ASP调用SQL中的图像
用排序串字段实现树状结构(例程:连接字串)
用排序串字段实现树状结构(例程:删除贴子)
用排序串字段实现树状结构(例程:回复表单)
用排序串字段实现树状结构(例程:显示贴子内容)
用排序串字段实现树状结构(例程:显示树)
用排序串字段实现树状结构(存储过程)
用排序串字段实现树状结构(库结构)
用排序串字段实现树状结构(原理)
remote script文档(转载自微软)(一)
remote script文档(转载自微软)(二)
remote script文档(转载自微软)(三)
remote script文档(转载自微软)(四)
remote script文档(转载自微软)(五)
remote script文档(转载自微软)(六)
remote script文档(转载自微软)(七)

ASP 中的 怎么样写一段高效,安全的sql查询代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 202 ::
收藏到网摘: n/a

  看一看这段代码,让我们来看看主要存在的问题

//设置SQL语句
insertstr="insert into userinfo(name,password,email,phone,mobile,post,address) VALUES(''";
insertstr += this._name.Trim()  
;+ "'',''";
insertstr += this._password.Trim() +"'',''";
insertstr += this._email.Trim() +"'',''";
insertstr += this._phone.Trim() +"'',''";
insertstr += this._mobile.Trim() +"'',''";
insertstr += this._post.Trim() +"'',''";
insertstr += this._address.Trim() +"'')";


1、效率问题
首先看看上边这段代码,效率太低了,这么多的字符串连接本身效率就够低的了,再加上这么些trim(),完全没有必要。

2、正确性问题
这段代码太脆弱,一个单引号就可以使整个程序崩溃。

3、安全性
同上,利用单引号我可以做很多事,比如运行个xp_cmd命令,那你就惨了,呵呵。

那么,怎样来写呢,上面这段代码可以改成这样:
string strSql = "insert into sometable (c1 , c2 , c3 , ...) values(@c1 , @c2 , @c3,...)"
SqlCommand myCommand = new SqlCommand(strSql , myConn)
try
{
myCommand.Parameters.Add(new SqlParameters("@c1" , SqlDataType.VarChar , 20)
myCommand.Parameters["@c1"].Value = this._Name ;
....
//有几个加几个
....
}
catch(...)
...

这样呢,既可以避免低效率的字符串连接,又可以利用sqlcommand参数有效性检测来避免非法字符的出现,并且由于这种parameter方式是预编译的,效率更高。

一举数得,何乐而不为呢。