2

如何SELECT从我的代码隐藏文件中执行查询,然后遍历它?

我想做这样的事情(只是一个简单的伪示例):

// SQL Server
var results = executeQuery("SELECT title, name FROM table");

foreach (var row in results)
{
    string title = row.title;
    string name = row.name;
}

我怎样才能在代码中做到这一点?

4

1 回答 1

7

像这样的东西:

 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["OrderID"], reader["CustomerID"]));
        }
    }
}

来源:http: //msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx

connectionString取决于数据库产品和使用的身份验证机制(Windows 身份验证、用户名/密码等)。上面的示例假设您使用的是 SQL Server。有关不同的完整列表ConnectionStrings,请访问http://www.connectionstrings.com/

于 2013-01-31T14:50:07.190 回答