如何在C#中访问数据库

6
基本上,我想要一个简短的解释,告诉我如何在C#代码中访问SQL数据库。我知道需要一个连接和一个命令,但是具体怎么做呢?我想请人把这个过程简单化一点。谢谢。
为了明确起见,在我的情况下,我正在做网络应用程序、电子商务等方面。所有都是ASP.NET、C#和SQL数据库。
我将关闭此主题。它有些太笼统了,我会发布一些更具针对性和教程风格的问题和答案。
10个回答

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()”时,读取器将包含新行。

然后关闭读取器,并因为我们正在退出“using”块,所以连接也会被关闭。


编辑:如果您正在寻找有关在ASP.NET中选择/更新数据的信息,则4GuysFromRolla有一个非常好的ASP.NET 2.0数据源控件的多部分系列

编辑2:正如其他人指出的那样,如果您使用的是较新版本的.NET,则建议研究LINQ。可以在此MSDN页面上找到介绍、示例和文档。


如果命令和连接仅在当前方法中使用,最好使用using语句对其进行作用域限定。 - Eric Schoonover
我同意,但是MSDN似乎在初学者文章中没有这样做(我从中复制并粘贴了这个),所以我认为这应该没问题。 - Espo
我能理解那些不遵循“最佳实践”的示例的逻辑,以免混淆事情。但在我看来,释放数据库连接是如此基础(特别是在Web应用程序中 - OP正在谈论ASP.NET),以至于它应该始终包括在内。来吧,更新你的示例 :) - Joe
学习这种老方法,当Linq已经出现似乎有点毫无意义。为什么要学习一种旧技术,而不是使用更快、更简单、更强大的方法呢? - naspinski

4

随着LINQ的出现,旧的ADO.Net(sqlConnection等)已经过时了。LINQ需要.Net 3.5,但与所有.Net 2.0+和Visual Studio 2005等向后兼容。

开始使用LINQ非常简单。

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

现在,您已经构建了一些类。您构建了exampleDataContext类,它是您的linq初始化程序,并且您构建了item类,它是items表中对象的类。这是自动完成的,您不需要担心它。现在假设我想获取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的新项目... 现在,如果你想从项目中获取一些信息,只需像这样调用它:

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

Linq非常容易使用!这只是冰山一角。

当你有一个更强大、更容易使用的工具时,就不需要学习过时的ADO了:)


3

非常初学者的问题,因此有标签。感谢提供链接!我喜欢那些动起来的漂亮图片! - MrBoJangles

1

连接/操作SQL服务器数据库的方法:

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)都具有类似的连接和操作界面。


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();
}

1

需要关注的主题:

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

1

1

1
我也建议使用数据集(DataSets)。 它们非常容易使用,只需要点击几下鼠标,不需要编写任何代码,对于小型应用来说足够好用。

1
如果您使用的是Visual Studio 2008,我建议跳过ADO.NET,直接使用LINQ to SQL。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接