[英]How to retrieve multiple values of single column in session
Each user on my website has a reg_id
. 我网站上的每个用户都有一个
reg_id
。 There are some emergency_contact_id
's associated with this reg_id
. 有一些
emergency_contact_id
的与此相关的reg_id
。
For example: 例如:
EmerContact_id Reg_id
91 1
92 1
93 1
94 1
95 1
Now I want to store these EmerContact_id
's into session like this: 现在,我想将这些
EmerContact_id
存储到会话中,如下所示:
Session["Emer1"]
Session["Emer2"]
Session["Emer3"]
Session["Emer4"]
Session["Emer5"]
How can I achieve this? 我该如何实现?
I am thinking of using: 我正在考虑使用:
while(reader.read()) { ... }
But I don't know how to use it. 但是我不知道如何使用它。
You can store complete list or dataset in session, however its not recommended but you can do it. 您可以在会话中存储完整列表或数据集,但是不建议这样做,但是您可以这样做。
When fetching you can cast it to the desired type. 提取时,可以将其转换为所需的类型。
Simple and easy 简单容易
If I understood your question.... 如果我理解您的问题...
Please try this 请尝试这个
string[] EmerContactList = new string[]{"Emer1","Emer2","Emer3"};
Session["values"] = EmerContactList ;
To access 进入
string[] results= (string[])Session["values"];
You can use MySqlDataReader
and iterate through your results using an index marker, like this. 您可以使用
MySqlDataReader
并使用索引标记对结果进行迭代,如下所示。
using (MySqlConnection dbConnection = new MySqlConnection("connectionstring"))
{
dbConnection.Open();
using (MySqlCommand dbCommand = new MySqlCommand("select EmerContact_id from [Table] order by EmerContact_id asc;", dbConnection))
{
using (MySqlDataReader dbReader = dbCommand.ExecuteReader())
{
int index = 1;
while (dbReader.Read())
{
Session["Emer" + index.ToString()] = dbReader[0].ToString();
index++;
}
}
}
dbConnection.Close();
}
You could also use a collection object like List
and serialize this into the session. 您还可以使用诸如
List
类的集合对象,并将其序列化到会话中。
You could also use one session object to store the values... 您还可以使用一个会话对象来存储值...
List<int> EmerContacts = new List<int>();
using (MySqlConnection dbConnection = new MySqlConnection("connectionstring"))
{
using (MySqlCommand dbCommand = new MySqlCommand("select EmerContact_id from [Table];", dbConnection))
{
using (MySqlDataReader dbReader = dbCommand.ExecuteReader())
{
while (dbReader.Read())
{
EmerContacts.Add((int)dbReader[0].ToString());
}
}
}
}
Session["EmerContacts"] = EmerContacts;
When you need to use the list then, you can just convert the session back to List... 然后,当您需要使用列表时,只需将会话转换回列表...
List<int> myList = (List<int>)Session["EmerContacts"];
I hand typed some of it, so it may not compile, but you should get the gist of it. 我手动输入了一些内容,因此它可能无法编译,但是您应该了解它的要旨。
When you use this approach, you can then easily itterate over the collection. 使用此方法时,您可以轻松地在集合上进行提示。 Using your approach makes this a bit more difficult.
使用您的方法会使这变得更加困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.