在用下拉框勾选查询的时候,需要组合条件,但是c#里面没有Java类似mybatis框架能直接在mapper.xml生成动态sql,因为这里我就用了sql拼接(跟字符串拼接一样)。
DataSource ds = new DataSource();
SqlConnection conn = ds.GetConn();
conn.Open();
string sql ="select * from test1 where 1=1";
String sqlWhere = "";
if (!comboBox1.ValueMember.ToString().Equals(""))
{
sqlWhere += $" and (MaterialNumber = '{comboBox1.SelectedValue.ToString()}')";
}
if (!comboBox2.ValueMember.ToString().Equals(""))
{
sqlWhere += $" and (GroupNumber = '{comboBox2.SelectedValue.ToString()}')";
}
if (!comboBox3.ValueMember.ToString().Equals(""))
{
sqlWhere += $" and (ProduceNumber = '{comboBox3.SelectedValue.ToString()}')";
}
sql += sqlWhere;
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = comm;
DataSet dt = new DataSet();
sda.Fill(dt);
gridControl1.DataSource = dt.Tables[0];
conn.Close();
其实很像mybatis 映射文件的动态sql机制。