如何在C#中访问数据库

时间:2008-09-18 06:31:39

标签: c# asp.net sql

基本上,我想简要解释一下如何使用C#代码访问SQL数据库。我认为需要连接和命令,但是发生了什么?我想我要问的是有人让这个过程神秘化了一下。感谢。

为了清楚起见,在我的情况下,我正在做网络应用程序,电子商务的东西。它是所有ASP.NET,C#和SQL数据库。

我要继续关闭这个帖子。这是一般性的,我将发布一些更尖锐和教程式的问题和答案。

10 个答案:

答案 0 :(得分:10)

MSDN在这里写得非常好:

http://msdn.microsoft.com/en-us/library/s7ee2dwt(VS.71).aspx

您应该查看数据读取器以获取简单的select语句。来自MSDN页面的示例:

private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

它基本上首先创建一个SqlConnection对象,然后创建SqlCommand - 包含您将要执行的实际选择的对象,以及对我们刚刚创建的连接的引用。然后它打开连接,在下一行,执行语句并返回SqlDataReader对象。

在while循环中,它然后输出阅读器第一行的值。每次调用“reader.Read()”时,阅读器都会包含一个新行。

然后读者关闭,因为我们退出“使用” - 秘密,连接也被关闭。


编辑:如果您正在寻找有关在ASP.NET中选择/更新数据的信息,4GuysFromRolla有一个非常好的Multipart Series on ASP.NET 2.0's Data Source Controls

EDIT2:正如其他人所指出的,如果您使用的是较新版本的.NET,我建议您查看LINQ。可以在this MSDN page上找到介绍,样本和写作。

答案 1 :(得分:4)

旧的ADO.Net(sqlConnection等)是LINQ出现的恐龙。 LINQ需要.Net 3.5,但向后兼容所有.Net 2.0+和Visual Studio 2005等。

从linq开始是非常容易的。

  • 在项目中添加一个新项目,一个 linq-to-sql 文件,这个文件将放在 App_Code 文件夹中(对于此示例,我们将调用它 example.dbml
  • 从您的服务器资源管理器中,将数据库中的表拖到dbml中(在此示例中,该表将命名为 items
  • 保存dbml文件

您现在已经构建了一些类。您构建了 exampleDataContext 类,它是您的linq初始化程序,并构建了类,该类是表中对象的类。这一切都是自动完成的,您无需担心。现在说我希望记录 itemID 为3,这就是我需要做的:

exampleDataContext db = new exampleDataContext(); // initializes your linq-to-sql
item item_I_want = (from i in db.items where i.itemID == 3 select i).First(); // using the 'item' class your dbml made

这就是全部。现在您有了一个名为 item_I_want 的新 ...现在,如果您想要中的一些信息,您只需将其称为:< / p>

int intID = item_I_want.itemID;
string itemName = item_I_want.name;

Linq 非常简单易用!这只是冰山一角。

当您拥有更强大,更轻松的工具时,无需学习过时的ADO:)

答案 2 :(得分:3)

读起来像一个初学者的问题。这需要初学者视频演示。

http://www.asp.net/learn/data-videos/

它们以ASP.NET为重点,但要注意数据库方面。

答案 3 :(得分:1)

要查看的主题:

  1. ADO.NET基础
  2. LINQ to SQL
  3. 托管数据库提供程序

答案 4 :(得分:1)

如果它是一个Web应用程序,这里有一些很好的资源来开始.NET中的数据访问:

http://weblogs.asp.net/scottgu/archive/2007/04/14/working-with-data-in-asp-net-2-0.aspx

答案 5 :(得分:1)

在SQL服务器db上连接/执行操作:

using System.Data;
using System.Data.SqlClient;

string connString = "Data Source=...";
SqlConnection conn = new SqlConnection(connString); // you can also use ConnectionStringBuilder
connection.Open();

string sql = "..."; // your SQL query
SqlCommand command = new SqlCommand(sql, conn);

// if you're interested in reading from a database use one of the following methods

// method 1
SqlDataReader reader = command.ExecuteReader();

while (reader.Read()) {
    object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index
}

// make sure you close the reader when you're done
reader.Close();

// method 2
DataTable table;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);

// then work with the table as you would normally

// when you're done
connection.Close();

大多数其他数据库服务器(如MySQL和PostgreSQL)都有类似的连接和操作接口。

答案 6 :(得分:1)

如果您正在寻找的是一个易于学习的教程,那么您应该访问www.ASP.net网站。

以下是初学者视频页面的链接:http://www.asp.net/learn/videos/video-49.aspx

以下是视频,如果您要下载它:video download

以下是视频中的C#项目链接:download project

祝你好运。

答案 7 :(得分:1)

我还建议使用DataSet。它们非常易于使用,只需点击几下鼠标,无需编写任何代码,也足以满足小型应用程序的要求。

答案 8 :(得分:1)

如果您有Visual Studio 2008,我建议您跳过ADO.NET并直接跳到LINQ to SQL

答案 9 :(得分:1)

@J D OConal基本上是正确的,但你需要确保你处理你的连接:

string connString = "Data Source=...";
string sql = "..."; // your SQL query

//this using block
using( SqlConnection conn = new SqlConnection(connString) )
using( SqlCommand command = new SqlCommand(sql, conn) )
{
    connection.Open();

    // if you're interested in reading from a database use one of the following methods

    // method 1
    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read()) {
        object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index
    }

    // make sure you close the reader when you're done
    reader.Close();

    // method 2
    DataTable table;
    SqlDataAdapter adapter = new SqlDataAdapter(command);
    adapter.Fill(table);

    // then work with the table as you would normally

    // when you're done
    connection.Close();
}
相关问题