How do I connect to a SQL database from C#?

后端 未结 8 1375
-上瘾入骨i
-上瘾入骨i 2020-12-02 19:06

I am trying to write a local program management and install system for my home network, and I think I\'ve got the technologies nailed down:

  • C#/.NET/WPF for the
相关标签:
8条回答
  • 2020-12-02 20:07

    Currently the easiest way to connect to your database and perform queries in C# is LinqToSQL. It will save you a lot of headache as compared to using "old-school" ADO connections.

    0 讨论(0)
  • 2020-12-02 20:08

    Check out

    • Introduction to ADO.NET Tutorial
    • ADO.NET Tutorial Lesson 1
    • An introduction to ADO.NET

    I'm sure there's plenty more out there - just google for "ADO.NET" and "Tutorial" ......

    UPDATE:

    If you want to connect to your local SQL Server Express, and connect to the "Northwind" database, and read the top 5 customers from the "Customers" table, you'd have to do something like this:

    string connectionString = "server=(local)\SQLExpress;database=Northwind;integrated Security=SSPI;";
    
    using(SqlConnection _con = new SqlConnection(connectionString))
    {
       string queryStatement = "SELECT TOP 5 * FROM dbo.Customers ORDER BY CustomerID";
    
       using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
       {
          DataTable customerTable = new DataTable("Top5Customers");
    
          SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
    
          _con.Open();
          _dap.Fill(customerTable);
          _con.Close();
    
       }
    }
    

    Now you would have all 5 top customers from your Northwind database in the DataTable and you can inspect them, print them out, manipulate them - whatever you want to do.

    That's ADO.NET in action!

    As for the details of the connection string - what options you can use and what it should look like, check out the Connection Strings web site - it has tons of examples and explanations.

    Marc

    0 讨论(0)
提交回复
热议问题