3

我知道这将非常简单。我见过很多在 asp.net 中使用 sql 的不同方法,但没有真正的标准。我想知道的是如何从 asp.net 中的 sql 数据库中干净地选择并检索多条记录。例如:选择所有用户标识。

String sql = 
  "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";

string strCon = System.Web
                      .Configuration
                      .WebConfigurationManager
                      .ConnectionStrings["SocialSiteConnectionString"]
                      .ConnectionString;

SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();

/*
 This is where I need to know how to retrieve the information from the
 above command(comm). I am looking for something similiar to php's
 mysql_result. I want to access the records kind of like an array or some
 other form of retrieving all the data.
 Also when the new SqlCommand is called...does that actual run the
 SELECT STATEMENT or is there another step. 
*/

conn.Close();
4

5 回答 5

6

我认为这就是你要找的。

String sql = "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'";

string strCon = System.Web
                      .Configuration
                      .WebConfigurationManager
                      .ConnectionStrings["SocialSiteConnectionString"].ConnectionString;

SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader nwReader = comm.ExecuteReader();
while (nwReader.Read())
{
    int UserID = (int)nwReader["UserID"];
    // Do something with UserID here...
}
nwReader.Close();
conn.Close();

不过,我不得不说,整体方法可以使用很多调整。首先,您至少可以从简化对 ConnectionString 的访问开始。例如,您可以将以下内容添加到 Global.asax.cs 文件中:

   using System;
   using System.Configuration;

   public partial class Global : HttpApplication
   {
      public static string ConnectionString; 

      void Application_Start(object sender, EventArgs e)
      { 
          ConnectionString = ConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
      }
      ...
    }

现在,在整个代码中,只需使用以下命令访问它:

SqlConnection conn = new SqlConnection(Global.ConnectionString);

更好的是,创建一个隐藏“管道”的类。要在我的代码中运行相同的查询,我只需输入:

        using (BSDIQuery qry = new BSDIQuery())
        {
            SqlDataReader nwReader = qry.Command("SELECT...").ReturnReader();
            // If I needed to add a parameter I'd add it above as well: .ParamVal("CurrentUser")
            while (nwReader.Read())
            {
                int UserID = (int)nwReader["UserID"];
                // Do something with UserID here...
            }
            nwReader.Close();
        }

这只是一个使用我的DAL 的例子。但是,请注意没有连接字符串,没有创建或管理的命令或连接对象,只有一个“BSDIQuery”(除了显示的内容之外,它还做了很多不同的事情)。您的方法会因您最常执行的任务而异。

于 2009-03-31T21:18:48.737 回答
3

大多数时候,我使用这个(注意我也在使用连接池方法):

    public DataTable ExecuteQueryTable(string query)
    {
        return ExecuteQueryTable(query, null);
    }

    public DataTable ExecuteQueryTable(string query, Dictionary<string, object> parameters)
    {
        using (SqlConnection conn = new SqlConnection(this.connectionString))
        {
            conn.Open();

            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = query;

                if (parameters != null)
                {
                    foreach (string parameter in parameters.Keys)
                    {
                        cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
                    }
                }

                DataTable tbl = new DataTable();
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(tbl);
                }

                return tbl;
            }
        }
    }
于 2009-03-31T21:13:53.117 回答
2

这是对现有代码的改编:

String sql = "SELECT [UserId] FROM [UserProfiles] WHERE [UserId] != @CurrentUserId";

string strCon = System.Web
                      .Configuration
                      .WebConfigurationManager
                      .ConnectionStrings["SocialSiteConnectionString"].ConnectionString;

DataTable result = new DataTable();
using (var conn = new SqlConnection(strCon))
using (var cmd = new SqlCommand(sql, conn))
{
    cmd.Parameters.Add("@CurrentUserID", SqlDbType.Int).Value = CurrentUserID;
    conn.Open();

    result.Load(cmd.ExecuteReader());
}
于 2009-03-31T21:15:06.267 回答
1

创建 aSqlCommand根本不会执行它。

当您调用ExecuteReader或类似的东西时,该命令将被执行。

如果您想要将所有结果提取到内存中的东西,您应该查看DataSet/ DataTable这里有他们的教程- 或者网上还有很多其他的,任何像样的 ADO.NET 书籍也将涵盖它们。

如果您不想一次将它们全部提取到内存中,那么ExecuteReader它就是适合您的方法。这将返回一个SqlDataReader类似于数据库游标的 a - 它一次读取一行,并且您根据需要请求各个列,Read每次调用以获取下一行。

于 2009-03-31T21:10:28.553 回答
0

而在 PHP 中你会做类似的事情,

while ($row = mysql_fetch_array ($result)) 
{
  //this assumes you're doing something with foo in loop
  $foo = $row["userid"];

  //using $foo somehow
}

在 .NET 中,您可以做一些不同的事情。相信我,出身于 PHP 背景,从 PHP 过渡到 .NET 并不容易。有很多事情看起来很奇怪。不过过一段时间,就会明白了!坚持下去。我个人更喜欢它。

好的..假设你有一个像你说的那样的数据集,你可以做这样的事情,

//assuming you have a DataSet called myDataSet
for (int i = 0; i < myDataSet.Tables[0].Rows.Count; i++)
{
  //likewise assuming here you're doing something with foo in loop
  string foo = myDataSet.Tables[0].Rows[i]["userid"].ToString();

  //similarly do something with foo in loop
}

这与 PHP 片段的作用相同。

于 2009-03-31T21:25:05.867 回答