The first article is exciting today! Here is an article about SQL composite query (multiple where conditions are dynamically generated)

Source: Internet
Author: User

// Name field corresponding to textbox1
// The password field corresponding to textbox2
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 button#click (Object sender, eventargs E)
{

If (textbox1.text. Trim (). Length = 0 & this. textbox1.text. Trim (). Length = 0)
{
MessageBox. Show ("incomplete data ");

}
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. Maid = DT. defaultview;
// SQL = "";
}
}
}

This is a winform. With "where 1 = 1", I feel that the super-powerful function can implement queries with multiple conditions without a lot of code, that is, dynamically generate multiple where and .. and .. and SQL statement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.