一个简单的SQL查询语句,
太阳丛 2009-07-03 12:23:56 在WINFORM窗体中,有这么几个控件:checkbox1, checkbox2,checkbox3 textbox1,textbox2,textbox3,
button1, datagridview1 表名是 student 有三个字段 ID name telephone
当点击button1时,根据textbox中的输入进行查询
在button1中的代码如下(直接打的,没有在VC里写):
string aa="",bb="",cc="";
if (checkbox1.checked==true)
{ aa= textbox1.text;}
else
{ aa="ID";}
if (checkbox2.checked==true)
{ bb= textbox2.text;}
else
{ bb="name";}
if (checkbox3.checked==true)
{ cc= textbox3.text;}
else
{ cc="telephone";}
string strsel="select * from student where ID="+aa+" and name="+bb+" and telephone="+cc+"";
datafridview1.datasource=connection.dset(strsel).table[0];
说明下,“connection”是我写的一个方法类,贴出来吧:
class connection
{
public static DataSet dtset(string str)
{ string strsqlcn = "Initial Catalog=school;Data Source=(local);Integrated Security=SSPI;";
SqlConnection cn = new SqlConnection(strsqlcn);
SqlDataAdapter adp = new SqlDataAdapter(str, cn);
DataSet dset = new DataSet();
adp.Fill(dset);
return dset;
}
}
个人认为问题的关键在SQL 语句,当checkbox都为FALSE 或第一个为true时,是没有问题,如果第一个checked为false ,就有问题了
还请高人指点下
另外说明下,此处主要用在对表的多条件混合查询中,用户可以自由选择查询条件,本来是要用IF {if {if{}else} else}ELSE
这种方式嵌套的,但是感觉不太好,所有就想了这么一段代码来实现目的