第一个文章,今天比较兴奋啊! 给大家一个关于SQL复合查询的文章(动态生成多个where条件)
//textbox1对应name字段
//textbox2对应password字段
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace FindRow
{
public partial class Form1 : Form
{
string sql;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length == 0 && this.textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("数据不完整");
}
else
{
if (this.textBox1.Text.Trim()!=string.Empty)
{
sql += "and name='" + textBox1.Text + "'";
}
if (this.textBox2.Text.Trim()!=string.Empty)
{
sql += "and password='" + textBox2.Text + "'";
}
a(sql);
sql = "";
}
}
public void a(string sql)
{
string strConn = "Data Source=(local);Initial Catalog=mydatabase;user id=sa;password=lansoft";
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from newTable where 1=1 " + sql;
DataTable dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(dt);
this.dataGridView1.DataSource = dt.DefaultView;
//sql = "";
}
}
}
这是一个WINFORM窗体,通过 "where 1=1 实现了这个我感觉超牛的功能 可以不用很多代码实现多个条件的查询,即动态生成多个 where and ..and..and SQL语句