技术开发 频道

ado.net获取数据库元数据信息


【IT168技术文档】

  DeriveParameters方法

  先说简单的一个。DeriveParameters是SqlCommandBuilder类的一个公共方法,提供一个SqlCommannd的参数,该Command对象作为获取到的Parameters的存放容器。其实SqlCommand本身就有一个DeriveParameters的方法,但是它是内部方法,而SqlCommandBuilder.DeriveParameters就是封装了该方法的调用:

1public static void DeriveParameters(SqlCommand command) 2{ 3 SqlConnection.SqlClientPermission.Demand(); 4 if (command == null) 5 { 6 // throw an exception 7 } 8 command.DeriveParameters(); 9}
  来看一下SqlCommand的DeriveParameters方法:
1internal void DeriveParameters() 2{ 3 4 // Validate command type(is storedprocedure?) and command info 5 6 7 // Retrieve command text detail 8 string[] txtCommand = ADP.ParseProcedureName(this.CommandText); 9 10 SqlCommand cmdDeriveCommand = null; 11 12 this.cmdText = "sp_procedure_params_rowset"; 13 if (txtCommand[1] != null) 14 { 15 this.cmdText = "[" + txtCommand[1] + "].." + this.cmdText; 16 17 if (txtCommand[0] != null) 18 { 19 this.cmdText = txtCommand[0] + "." + this.cmdText; 20 } 21 22 cmdDeriveCommand = new SqlCommand(this.cmdText, this.Connection); 23 } 24 else 25 { 26 cmdDeriveCommand = new SqlCommand(this.cmdText, this.Connection); 27 } 28 cmdDeriveCommand.CommandType = CommandType.StoredProcedure; 29 cmdDeriveCommand.Parameters.Add(new SqlParameter("@procedure_name", SqlDbType.NVarChar, 0xff)); 30 cmdDeriveCommand.Parameters[0].Value = txtCommand[3]; 31 ArrayList parms = new ArrayList(); 32 try 33 { 34 try 35 { 36 using (SqlDataReader drParam = cmdDeriveCommand.ExecuteReader()) 37 { 38 SqlParameter parameter = null; 39 while (drParam.Read()) 40 { 41 parameter = new SqlParameter(); 42 parameter.ParameterName = (string) drParam["PARAMETER_NAME"]; 43 parameter.SqlDbType = MetaType.GetSqlDbTypeFromOleDbType((short) drParam["DATA_TYPE"], (string) drParam["TYPE_NAME"]); 44 object len = drParam["CHARACTER_MAXIMUM_LENGTH"]; 45 if (len is int) 46 { 47 parameter.Size = (int) len; 48 } 49 parameter.Direction = this.ParameterDirectionFromOleDbDirection((short) drParam["PARAMETER_TYPE"]); 50 if (parameter.SqlDbType == SqlDbType.Decimal) 51 { 52 parameter.Scale = (byte) (((short) drParam["NUMERIC_SCALE"]) & 0xff); 53 parameter.Precision = (byte) (((short) drParam["NUMERIC_PRECISION"]) & 0xff); 54 } 55 parms.Add(parameter); 56 } 57 } 58 } 59 finally 60 { 61 cmdDeriveCommand.Connection = null; 62 } 63 } 64 catch 65 { 66 throw; 67 } 68 69 if (params.Count == 0) 70 { 71 // throw an exception that current storedprocedure does not exist 72 } 73 74 this.Parameters.Clear(); 75 foreach (object parm in parms) 76 { 77 this._parameters.Add(parm); 78 } 79}
0
相关文章