因存储过程参数类型不匹配而造成OleDbCommand的不可用
Key words:
Stored Procedure/OleDbCommand/Ado.Net/Parameter/Type/存储过程/参数/类型
在讨论OleDbCommand出错之前,还是想了解以下OleDbCommand一些运行机制。在数据库里面有如下存储过程:
ALTER PROCEDURE dbo.Test
@Name nvarchar(50),
@Age smallint
AS
select @Name, @Age
使用以下代码调用,并用Watch监视OleDbCommand实例的内存状况:
using System;
using System.Data;
using System.Data.OleDb;
namespace testCommand
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
OleDbConnection conn=new OleDbConnection("xxx");
conn.Open();
OleDbCommand comm=new OleDbCommand("Test",conn);
comm.CommandType=CommandType.StoredProcedure;
OleDbCommandBuilder.DeriveParameters(comm);
try
{
comm.Parameters["Name"].Value="my name";
comm.Parameters["Age"].Value=(object)11;
comm.ExecuteNonQuery(); //断点一,此处内存状况见表一
}
catch(Exception err)
{
Console.WriteLine(
err.TargetSite+"\r\n--\r\n"+err.StackTrace+"\r\n--\r\n"+
err.Source+"\r\n--\r\n"+err.Message+"\r\n--\r\n"+
err.GetType().ToString());
}
try
{
comm.Parameters["Name"].Value="my name";
comm.Parameters["Age"].Value=(object)11;
comm.ExecuteNonQuery(); //断点二,此处内存状况见表二
}
catch(Exception err)
{
Console.WriteLine(
err.TargetSite+"\r\n--\r\n"+err.StackTrace+"\r\n--\r\n"+
err.Source+"\r\n--\r\n"+err.Message+"\r\n--\r\n"+
err.GetType().ToString());
}
conn.Close();
}
}
}
表格一,断点一处的内存状况
-
comm
{System.Data.OleDb.OleDbCommand}
System.Data.OleDb.OleDbCommand
transaction
null
System.Data.OleDb.OleDbTransaction
cmdText
Test
string
cmdType
StoredProcedure
System.Data.CommandType
updatedRowSource
Both
System.Data.UpdateRowSource
commandTimeout
30
int
icommandText
null
System.Data.Common.UnsafeNativeMethods.ICommandText
handle_Accessor
0
int
commandBehavior
Default
System.Data.CommandBehavior
dbBindings
null
System.Data.OleDb.DBBindings
canceling
FALSE
bool
isPrepared
FALSE
bool
executeQuery
FALSE
bool
computedParameters
FALSE
bool
designTimeVisible
FALSE
bool
cmdState
0
int
recordsAffected
0
int
CommandText
Test
string
CommandTimeout
30
int
CommandType
StoredProcedure
System.Data.CommandType
DesignTimeVisible
TRUE
bool
IsClosed
TRUE
bool
Transaction
null
System.Data.OleDb.OleDbTransaction
UpdatedRowSource
Both
System.Data.UpdateRowSource