All,
I can't seem to find a good example of how to work with databases in C#. I'm using sqlserver and I can do simple things like insert and retrieve data, but when I am retrieving data I have to refer to the ordinal index values of the columns (reader[0], reader[1]) instead of the column names. I think this is stupid because I may not know what order the columns are in. Is there any way to modify this code to use column names instead of index values? Code sample is from: http://msdn.microsoft.com/en-us/library/dw70f090%28v=vs.80%29.aspx
Thanks,
Bill
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString =
"SELECT CategoryID, CategoryName FROM dbo.Categories;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}",
reader[0], reader[1]); //***I want to use column names here***
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=SSPI";
}
}