gpt4 book ai didi

Asp.Net 在 Sql 中选择

转载 作者:行者123 更新时间:2023-12-02 12:21:04 26 4
gpt4 key购买 nike

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

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

最佳答案

我认为这就是您正在寻找的。

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”(除了显示的内容之外,它还执行许多不同的操作)。根据您最常执行的任务,您的方法会有所不同。

关于Asp.Net 在 Sql 中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/703061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com