从 ADO.NET 结果集中检索各个列
我有一个网站,设置为查询数据库中的用户名,然后使用用户信息填充 Session[]
变量。当我使用服务器的存储过程进行查询时,我会返回整行。如何拆分行并解析它,以便单独解析每一列?
我的按钮代码是:
protected void Button4_Click(object sender, EventArgs e)
{
string strConn = WebConfigurationManager.ConnectionStrings["TicketsConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConn);
//Search button
string sqlText = ("select * from [dbo].[User]");
SqlCommand myCommand = new SqlCommand(sqlText,myConnection);
myCommand.CommandType = CommandType.Text;
myConnection.Open();
SqlDataReader objReader;
objReader = myCommand.ExecuteReader();
objGrid.DataSource = objReader;
objGrid.DataBind();
}
UPDATE
我将其更新为 string sqlText = ("select 'UserID', 'FirstName' from [dbo].[User] where UserID='"+txtTest .Text+"' 和 Password='" + txtPass.Text+"'");
但现在我得到以下列 栏 1 栏 2 用户 ID 名字
I have a website which is set to query a database for a username, and then populate the Session[]
variables with the user's info. When I query using the server's stored procedure, I get back the entire row. How can I split apart the row and parse it so that every column gets parsed separately?
My code for the button is:
protected void Button4_Click(object sender, EventArgs e)
{
string strConn = WebConfigurationManager.ConnectionStrings["TicketsConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(strConn);
//Search button
string sqlText = ("select * from [dbo].[User]");
SqlCommand myCommand = new SqlCommand(sqlText,myConnection);
myCommand.CommandType = CommandType.Text;
myConnection.Open();
SqlDataReader objReader;
objReader = myCommand.ExecuteReader();
objGrid.DataSource = objReader;
objGrid.DataBind();
}
UPDATE
I updated it to string sqlText = ("select 'UserID', 'FirstName' from [dbo].[User] where UserID='"+txtTest.Text+"' and Password='" + txtPass.Text+"'");
But now I get the following column
Column1 Column2
UserID FirstName
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要读取列的值,请使用以下命令:
To read a column's value use this:
而不是:
使用:
这将仅返回您需要的列。
* UPDATE *
对所有属性进行一系列查询绝对不是一个好的选择。您可以通过用逗号分隔来选择所需的所有列,如下所示:
然后您可以使用 SqlDataReader 索引器 获取您需要的值:
Instead of:
Use:
That will return just the column you need.
* UPDATE *
Making a series of queries for all the properties is definitely not a good option. You can select all the columns you need by separating by comma like this:
Then you can use the SqlDataReader indexer to get the values you need: