如何使用where语句创建具有两个条件的查询? [英] How do create a query with where statement with two conditions?

查看:161
本文介绍了如何使用where语句创建具有两个条件的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用where语句创建有两个条件的查询。



Is there any possible way to create query using where statement with two conditions.

    string connectionString = "Data Source=PD-JANAKAN;Initial Catalog=Enquiry;User ID=Madushan;Password=P@19861030";
    DataTable dt = new DataTable();
    SqlConnection connection = new SqlConnection(connectionString);
    SqlDataReader myReader = null;
    SqlCommand command = new SqlCommand("SELECT * FROM Enquiry where Cust_Name='" + myselection + "' or Cust_ID='" + vid + "'", connection);
    connection.Open();
    //command.Parameters.AddWithValue("@Cust_Name", myselection);
    myReader = command.ExecuteReader();


    while (myReader.Read())
    {
        Cus_Contact.Text = (myReader["Cust_Cntact"].ToString());
        DateTime Submit = (DateTime)myReader["Submit_Date"];
        DateTime Required = (DateTime)myReader["Req_Date"];
        More_Info.Text = (myReader["More_Details"].ToString());
        Stat_Sec.Text = (myReader["Sec_Status"].ToString());
    }
    connection.Close();
}

推荐答案

根据评论员的建议,让我们将其转移到商店程序中/>


您写道:

Well following the advice of the commentators, let's move it into a store procedure

You wrote:
"SELECT * FROM Enquiry where Cust_Name='" + myselection + "' or Cust_ID='" + vid + "'"





更改为:

关于mssql执行命令:

(数据类型应该与表中的数据类型匹配)





Change to:
On mssql execute command:
(datatypes should match those in your table)

create proc spSelectCustomerByNameAndID(
    @name nvarchar(50),
    @id nvarchar(50)
)
begin
   SELECT * FROM ENQUIRY WHERE CUST_NAME = @name AND CUST_ID = @id;
end





接下来来自你的C#这样的东西





Next up from your C# something like this

 using (SqlConnection con = new SqlConnection(connectionString)) {
    using (SqlCommand cmd = new SqlCommand("spSelectCustomerByNameAndID", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = myselection;
      cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = vidvar ;

      con.Open();
      var reader = cmd.ExecuteReader();

/* As i read your code you are assigning to variables, so your read loop should not iterate or you will only see the last row.*/
                        if(!reader.HasRows){
   //TODO: Handle situation where search yields no results
   return;
} 
                        reader.Read();
                       //TODO: Assign variables
    }
  }





在出口处,我想向您介绍为什么所有好人都在为不信​​任投入而感到悲伤,这就是真正的恐惧sql注入。检查来自UI的数据总是不是一个好主意,特别是如果它来自网络帖子或得到: https://technet.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx [ ^ ]


这篇关于如何使用where语句创建具有两个条件的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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