如何sqlconnection whith变量 [英] How to sqlconnection whith variables

查看:69
本文介绍了如何sqlconnection whith变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在使用下一个代码:



Hi

im using the next code:

using (SqlConnection con = new SqlConnection())
  {
      try
      {
          con.ConnectionString = "Data Source=PC;Persist Security Info=True;User ID=sa;Initial Catalog=XXXX; Password=XXXXX";
          con.Open();

          adap = new SqlDataAdapter("select Description, Status, Loc from TableKit where IdStatus = 1 and Idstore = 1", con);

          ds = new System.Data.DataSet();
          adap.Fill(ds, "Idkit_details");
          DataTable dstable = ds.Tables["Idkit_details"];





它的工作原理,但现在我需要在适应句中添加两个新参数



it Works, but now i need to add to the adap sentence two new parameters as

IdStatus 

Idstore 





不同的用户按钮

.

whith different user buttons

IdStatus 

Idstore 

获得不同的状态1,2,3但两者都是int



如何使用可变参数更改实际参数?



gets different states, 1,2,3 but both are a int

how i can change the actually parametres with a variable parameters?

adap = new SqlDataAdapter("select Description, Status, Loc from TableKit where IdStatus = 1 and Idstore = 1", con);





谢谢



我尝试过:





thanks

What I have tried:

adap = new SqlDataAdapter("select Description, Status, Loc from TableKit where IdStatus = 1 and Idstore = 1", con);

推荐答案

尝试



try

private void button1_Click(object sender, EventArgs e)
      {
          string statusCommaSeperatedValue = "1,2,3"; // get the value from any control (textbox or listbox or any input)
          string storeId = "1"; // get the value from any input

         DataTable dt =  GetData(statusCommaSeperatedValue,storeId);
      }

      private static DataTable GetData(string statusCommaSeperatedValue, string storeId)
      {
          DataTable dt = new DataTable();

              try
              {
                  SqlConnection con = new SqlConnection();
                  con.ConnectionString = "Data Source=PC;Persist Security Info=True;User ID=sa;Initial Catalog=XXXX; Password=XXXXX";
                  string query = "select Description, Status, Loc from TableKit where IdStatus in ( @status ) and Idstore = @store";
                  SqlCommand cmd = new SqlCommand(query, con);
                  cmd.Parameters.AddWithValue("@status", statusCommaSeperatedValue);
                  cmd.Parameters.AddWithValue("@store", storeId);
                  cmd.CommandType = CommandType.Text;
                  SqlDataAdapter adap = new SqlDataAdapter(cmd);
                  adap.Fill(dt);
              }
              catch (Exception ex)
              {
                  throw;
              }

          return dt;
      }
  }


这篇关于如何sqlconnection whith变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆