当前位置:编程学习 > C#/ASP.NET >>

在VS2005里 怎么获取sql语句的值!!谢谢了

sql语句:  Select count(编号) from 巡检记录 where 录入人='" + text1.Text + "' and 机井编号='" + TextBox1.Text + "' and 机井名称='" + DropDownList2.SelectedValue.ToString() + "' and 单位名称='" + DropDownList1.SelectedValue.ToString() + "'";

 也许我在text1里没有输入值(即我不用Text1为查询条件) 但是偶尔我也会用到Text1   请问我的SQL语句该怎么写呢???  --------------------编程问答-------------------- 搜StringBuilder的用法. --------------------编程问答-------------------- 哪位大侠能帮我把语句全写出来呀!! 谢了呀!! --------------------编程问答-------------------- StringBuilder sb = new StringBuilder();
sb.append(" Select count(编号) from 巡检记录 where 1=1");
if(!string.isnullorempty(text1.Text.Trim()))
     sb.append(" and 录入人='" + text1.Text + "'");
sb.append(" and 机井编号='" + TextBox1.Text + "' and 机井名称='" + DropDownList2.SelectedValue.ToString() + "' and 单位名称='" + DropDownList1.SelectedValue.ToString() + "'");

string sql=sb.ToString();

隨手寫的,未測試,大致思路是對的. --------------------编程问答-------------------- 小建议啊:不要这样直接拼接SQL语句,容易被SQL注入攻击,最好使用SQL参数!

参数@name 的值为textbox1的值。如果文本框没填值,就给@name 赋值null.就能达到你要的效果!
Select count(编号) from 巡检记录 where (录入人=@name or @name is null)
--------------------编程问答-------------------- string sql=string.format(Select count(编号) from 巡检记录 where 1=1 and {0} and 机井编号='{1}' and 机井名称='{2}' and 单位名称='{3}'",string.IsNullOrEmpty(text1.Text )?"":"录入人='" + text1.Text + "'",TextBox1.Text ,DropDownList2.SelectedValue.ToString() ,DropDownList1.SelectedValue.ToString() ); --------------------编程问答-------------------- 防止注入!使用sql参数吧 --------------------编程问答-------------------- 哈,有人比我菜了!太好了!
--------------------编程问答--------------------

            string sql = "Select count(编号) from 巡检记录 where (录入人='" + text1.Text + "' or isnull('" + text1.Text + "','')='') and 机井编号='" + TextBox1.Text + "' and 机井名称='" + DropDownList2.SelectedValue.ToString() + "' and 单位名称='" + DropDownList1.SelectedValue.ToString() + "'";
            


这样应该就可以了
(录入人='" + text1.Text + "' or isnull('" + text1.Text + "','')='')
当text1.Text有值的时候取前面的值,当没有值的是很or后面的横成立,所以根本不需要判断的

--------------------编程问答-------------------- 真惊了,你判断一下不就可以,当textbox==“”时,不加载查询条件
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,