View Single Post
  #2 (permalink)  
Old 06-25-2008, 10:52 AM
gaylo565's Avatar   
gaylo565 gaylo565 is offline
Programmer
 
Join Date: May 2007
Location: flagstaff, az
Posts: 187
Last Blog:
String Manipulation wi...
Rep Power: 9
gaylo565 is a jewel in the roughgaylo565 is a jewel in the roughgaylo565 is a jewel in the rough
Default Re: wild card string search in C#

Here is a simple example of an sql query executed in c# on the Northwind database that is included with sql express server. It gets all the specified rows from the Orders table who's Customer Id contains intCustomerID (The variable isn't defined in the scope of this code but can be retrieved from a text box or set some other way. It is called a parameter and is only there to narrow down our search.)
Code:
try
{
    Set up the data connection    
    DataConnection.ConnectionString = 
        "Integrated Security = true;"+
        "Initial Catalog = Northwind;"+
        "Data Scource = ServerName\\SQLEXPRESS";
    dataConnection.Open()
    SqlCommand dataCommand = new SqlCommand();
    dataCommand.Connection = dataConnection;
    //set up actual sql query
    dataCommand.CommandText =
        "SELECT OrderID, OrderDate, "+
        "ShipName";
    //You can do this all in one command but 
    //I split it up to make it easier to read    
    dataCommand.CommandText +=
        "FROM Orders WHERE CustomerID '"+intCustomerID+"'";
    //call dataReader class to execute dataCommand
    SqlDataReader = dataCommand.ExecuteReader();
    //create loop to iterate through the records;
    while (dataReader.Read())
    {
        //Do something with your returned records
        intorderId = dataReader.GetInt32(0):
        if(dataReader.IsDBNull(2)
        {
             MessageBox.Show("Order {0} not yet shipped)
        }
        else
        {
            DateTime orderDate = dataReader.GetDateTime(1);
            string shipName = dataReader.GetString(3);
        }
    }
    dataReader.Close();
}
catch(Exception e)
{
    MessageBox.Show(e.Message, "Error accessing the database:", MessageBoxButtons.OK);
}
finally
{
    dataConnection.Close()
}
Keep in mind this is a very simple example. You should also look into creating a data set for your information. The method I used above locks th rows being queried while in use and is therefor considered inefficient for multiuser db applications. A data set is more complicated but worth learning for the sort of application you want to build.
This is a decent intro to data sets: Using the DataSet - Using ADO.NET with SQL Server - Developer Fusion - Visual Basic, C# Programming, ASP.NET, .NET Framework and Java Tutorials

Last edited by gaylo565; 06-25-2008 at 11:52 AM.
Reply With Quote