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