C# Database Connection coding

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Newbie19
    New Member
    • Jun 2007
    • 122

    C# Database Connection coding

    I'm not sure where to put this question since there isn't a C# section, but since it is apart of the .net family I'll start here. I'm trying to connect my C# API to a Sql Database to pull data. However, every site I've found so far has given me examples that don't seem to work.

    What is the best way to connect to a database via C#?

    Thanks.
  • talhaekram
    New Member
    • Apr 2007
    • 14

    #2
    [CODE=css]try
    {
    SqlConnection thisConnection = new SqlConnection(@ "...");
    thisConnection. Open();
    SqlCommand thisCommand = thisConnection. CreateCommand() ;
    thisCommand.Com mandText = "SELECT CustomerID, CompanyName FROM Customers";
    SqlDataReader thisReader = thisCommand.Exe cuteReader();
    while (thisReader.Rea d())
    {
    Console.WriteLi ne("\t{0}\t{1}" , thisReader["CustomerID "], thisReader["CompanyNam e"]);
    }
    thisReader.Clos e();
    thisConnection. Close();

    }
    catch (SqlException e)
    {
    Console.WriteLi ne(e.Message);
    }
    [/CODE]
    ref::http://www.daniweb.com
    Last edited by r035198x; Sep 8 '07, 08:04 AM. Reason: Linking to other forums is against site rules

    Comment

    • Newbie19
      New Member
      • Jun 2007
      • 122

      #3
      Thanks for the help.

      Comment

      Working...