第一个文章,今天比较兴奋啊! 给大家一个关于SQL复合查询的文章(动态生成多个where条件)...

本文介绍了一种使用C#在WinForms应用程序中实现动态SQL查询的方法。该方法能够根据用户输入自动生成包含多个条件的SQL语句,实现灵活的数据检索。文章通过具体示例展示了如何构建SQL查询语句并执行查询。

//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语句

转载于:https://www.cnblogs.com/bnjbl/archive/2007/05/11/742571.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值