【问题标题】:How to use a DataAdapter with stored procedure and parameter如何使用带有存储过程和参数的 DataAdapter
【发布时间】:2011-04-01 11:52:43
【问题描述】:

我想使用 DataAdapter 填充 DataGridView 控件。但我不知道该怎么做,因为我使用的是带参数的存储过程。 有人可以举个例子吗?

【问题讨论】:

  • 这是一个 Microsoft article,它提供了一个这样做的例子。

标签: c# stored-procedures dataadapter


【解决方案1】:

我明白了!...呵呵

protected DataTable RetrieveEmployeeSubInfo(string employeeNo)
        {
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();
            try
            {
                cmd = new SqlCommand("RETRIEVE_EMPLOYEE", pl.ConnOpen());
                cmd.Parameters.Add(new SqlParameter("@EMPLOYEENO", employeeNo));
                cmd.CommandType = CommandType.StoredProcedure;
                da.SelectCommand = cmd;
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
            catch (Exception x)
            {
                MessageBox.Show(x.GetBaseException().ToString(), "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cmd.Dispose();
                pl.MySQLConn.Close();
            }
            return dt;
        }

【讨论】:

  • 一种更简洁的方法是将 IDisposable 资源包装在 using 子句中,而不是 try finally
  • ^更清洁使用Using
  • 这非常有效。但是我在使用适配器更新数据库时遇到了问题!我在stackoverflow中发布了一个问题,但没有得到任何回复。请看看我的问题:stackoverflow.com/questions/52839136/…
  • @HilalAl-Rajhi 您的链接已被版主删除 - 可能是因为这是一个重复的问题。我意识到我迟到了 3 年,但你基本上和上面一样,但是在 Parameters.Add 命令之外实例化 SqlParameter,并给它一个输入方向,然后添加它:SqlParameter param = new SqlParameter("@EMPLOYEENO", employeeNo); param.Direction = ParameterDirection.Input; cmd.Parameters.Add(param); 见@ 987654322@
【解决方案2】:
 SqlConnection con = new SqlConnection(@"Some Connection String");
 SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;

【讨论】:

    【解决方案3】:

    也许您的代码缺少 Microsoft 示例中的这一行:

    MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
    

    【讨论】:

      【解决方案4】:
          SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
              builder.DataSource = <sql server name>;
              builder.UserID = <user id>; //User id used to login into SQL
              builder.Password = <password>; //password used to login into SQL
              builder.InitialCatalog = <database name>; //Name of Database
      
              DataTable orderTable = new DataTable();
      
              //<sp name> stored procedute name which you want to exceute
              using (var con = new SqlConnection(builder.ConnectionString))
              using (SqlCommand cmd = new SqlCommand(<sp name>, con)) 
              using (var da = new SqlDataAdapter(cmd))
              {
                  cmd.CommandType = System.Data.CommandType.StoredProcedure;
                  //Data adapter(da) fills the data retuned from stored procedure 
                 //into orderTable
                  da.Fill(orderTable);
              }
      

      【讨论】:

      • 感谢您使用“使用”语法。
      【解决方案5】:

      又短又甜……

      DataTable dataTable = new DataTable();
      try
      {
         using (var adapter = new SqlDataAdapter("StoredProcedureName", ConnectionString))
         {
             adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
             adapter.SelectCommand.Parameters.Add("@ParameterName", SqlDbType.Int).Value = 123;
             adapter.Fill(dataTable);
         };
      }
      catch (Exception ex)
      {
          Logger.Error("Error occured while fetching records from SQL server", ex);
      }
      

      【讨论】:

      • 如果您能提供代码的解释,我们将不胜感激。
      • 解释如何使用 SQLDataAdapter 和存储过程填充数据表的代码。
      【解决方案6】:

      我们来了,

      DataSet ds = new DataSet();
      SqlCommand cmd = new SqlCommand();
      cmd.Connection = con; //database connection
      cmd.CommandText = "WRITE_STORED_PROC_NAME"; //  Stored procedure name
      cmd.CommandType = CommandType.StoredProcedure; // set it to stored proc
      //add parameter if necessary
      cmd.Parameters.Add("@userId", SqlDbType.Int).Value = courseid;
      
      SqlDataAdapter adap = new SqlDataAdapter(cmd);
      adap.Fill(ds, "Course");
      return ds;
      

      【讨论】:

        【解决方案7】:
           public DataSet Myfunction(string Myparameter)
            {
                config.cmd.Connection = config.cnx;
                config.cmd.CommandText = "ProcName";
                config.cmd.CommandType = CommandType.StoredProcedure;
                config.cmd.Parameters.Add("parameter", SqlDbType.VarChar, 10);
                config.cmd.Parameters["parameter"].Value = Myparameter;
        
                config.dRadio = new SqlDataAdapter(config.cmd);
                config.dRadio.Fill(config.ds,"Table");
        
                return config.ds;
        
        
            }
        

        【讨论】:

          【解决方案8】:
          SqlConnection con = new SqlConnection(@"Some Connection String");//connection object
          SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);//SqlDataAdapter class object
          da.SelectCommand.CommandType = CommandType.StoredProcedure; //command sype
          da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123; //pass perametter
          DataTable dt = new DataTable();  //dataset class object
          da.Fill(dt); //call the stored producer
          

          【讨论】:

            【解决方案9】:
            public class SQLCon
            {
              public static string cs = 
               ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                SqlDataAdapter MyDataAdapter;
                SQLCon cs = new SQLCon();
                DataSet RsUser = new DataSet();
                RsUser = new DataSet();
                using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
                   {
                    MyConnection.Open();
                    MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
                    //'Set the command type as StoredProcedure.
                    MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
                    RsUser = new DataSet();
                    MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID", 
                    SqlDbType.Int));
                    MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
                    MyDataAdapter.Fill(RsUser, "GetAPPID");
                   }
            
                  if (RsUser.Tables[0].Rows.Count > 0) //data was found
                  {
                    Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
                   }
                 else
                   {
            
                   }    
            }    
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2020-02-12
              • 2011-09-18
              • 2012-01-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多