您的位置:首页 > 数据库

C# 调用SQL的存储过程的接口及实现

2013-07-10 15:42 381 查看
1. 接口为ExecuteStoredProcedure(string storedProcedureName, params ObjectParameter[] parameters)
2. 参数为存储过程名字, 及输入值。
3. 思路:创建连接(连接中指定了是Sql/MySql/ODBC等等); 创建通用DbCommand;更改Text以及Type;添加通用Parameter(DBParameter是抽象类,因此需要判断connection类型);判断连接状态(需Open); 调用Execute方法; 关闭连接。
4.
实现如下:
// In V1 of the EF, the context connection is always an EntityConnection                 EntityConnection entityConnection = (EntityConnection)protocolDB.Connection;                   // The EntityConnection exposes the underlying store connection                 DbConnection storeConnection = entityConnection.StoreConnection;                 DbCommand command = storeConnection.CreateCommand();                 command.CommandText = storedProcedureName;                 command.CommandType = CommandType.StoredProcedure;                   if (storeConnection is SqlConnection)                 {                     foreach (ObjectParameter p in parameters)                     {                         command.Parameters.Add(new SqlParameter { ParameterName = p.Name, Value = p.Value });                     }                 }                 else if (storeConnection is MySqlConnection)                 {                     foreach (ObjectParameter p in parameters)                     {                         command.Parameters.Add(new MySqlParameter { ParameterName = p.Name, Value = p.Value });                     }                 }                 else                 {                     return enProtocolDBReturnCodes.OPERATION_FAILED;                 }                   bool openingConnection = command.Connection.State == ConnectionState.Closed;                 if (openingConnection)                 {                     command.Connection.Open();                 }                   command.ExecuteNonQuery();                   if (openingConnection && command.Connection.State == ConnectionState.Open)                 {                      command.Connection.Close();                 }
本文出自 “木子纵横” 博客,请务必保留此出处http://muzizongheng.blog.51cto.com/856912/1333047
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: