VB数据库操作---ADODB.Command 终结所有SQL注入

演示了command的使用。另外还有设置参数,防止注入,不太明白。

http://blog.csdn.net/kj021320/article/details/1689960

通常为了省事 程序员都喜欢直接采用Connection的execute方法,SQL是拼凑出来的!当然很容易出现问题了~~而很多人都知道 Command可以用来执行存储过程

其实Command 直接执行SQL性能效率更好,而且更安全,有点像JAVA里面的PreparedStatement 同构的SQL语句.....

以下我建立了一个ACCESS的数据库叫 kj021320.mdb

其中有一个表 nonamed 字段 name 文本类型 class 数字类型

OK 手工往表里面插入2条数据

name class

aaa\' 1

b\'b 2

下面来看看command CommandType的枚举值代表的意思~我们将用到 adCmdText

CommandTypeEnum Values

Constant

常量

Value

Description

描述

adCmdUnspecified

-1

Does not specify the command type argument.

不指定指令类型自变量

adCmdText

1

Evaluates CommandText as a textual definition of a command or stored procedure call.

指示提供者应该将Source作为命令的文本定义来计算。

adCmdTable

2

Evaluates CommandText as a table name whose columns are all returned by an internally generated SQL query.

指示ADO生成SQL查询以便从在Source中命名的表中返回所有行

adCmdStoredProc

4

Evaluates CommandText as a stored procedure name.

将CommandText作为一个已存的程序名称

adCmdUnknown

8

Default. Indicates that the type of command in the CommandText property is not known.

默认值。指定未知的CommandText属性命令

adCmdFile

256

Evaluates CommandText as the file name of a persistently stored Recordset. Used with Recordset.Open or Requery only.

指示应从在Source中命名的文件中恢复保留(保存的)Recordset。它仅能与Recordset.Open 或 Requery 指令一起使用

adCmdTableDirect

512

Evaluates CommandText as a table name whose columns are all returned. Used with Recordset.Open or Requery only. To use the Seek method, the Recordset must be opened with adCmdTableDirect. This value cannot be combined with the ExecuteOptionEnum value adAsyncExecute.

指示提供者更改从在 Source 中命名的表中返回所有行 /

将CommandText作为一个表的名称(该表的列全部是通过内部的SQL查询语句返回的)。它仅适用Recordset.Open 或 Requery 指令;如果需要使用查找方式,那么Recordset必须以adCmdTableDirect打开。这个值不能与ExecuteOptionEnum值 adAsyncExecute一起使用

看以下VB代码

Dim cmd As New ADODB.Command
Dim conn As New ADODB.Connection
Dim connString, nameStr, classNum, rs
connString = "provider=microsoft.jet.oledb.4.0;data source=E:/kj021320.mdb;"
conn.Open connString
cmd.ActiveConnection = conn
cmd.CommandType = adCmdText

\'Print adVarChar
\'Print adParamInput
\'Print cmd.Dialect
cmd.CommandText = "select * from nonamed where name=@n"
cmd.Parameters.Append cmd.CreateParameter("@n", adVarChar, adParamInput, 100, "aaa\'")
Set rs = cmd.Execute
Print rs("class")
Print rs("name")
\'cmd.CommandText = "select * from STU where class=@c"
\'cmd.Parameters.Append cmd.CreateParameter("@c", adBigInt, adParamInput, , "1")
\'Set rs = cmd.Execute
conn.Close

打印出来

1

aaa\'