![](/img/trans.png)
[英]How to assign an ID value to each added row in a .txt file (ASP.NET MVC / C#)
[英]How to get all the values in a row of a DB relation and assign each of them to a variable in ASP.NET C#
我正在嘗試找到一種方法來訪問連續的所有值。
以下代碼返回一個單元格。 如果我將select id
更改為select *
,我可以訪問該行,但如何將其分開?
string find_user = "select id from users where userName = '" + un + "'";
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand(find_user, con))
{
con.Open();
user_id = cmd.ExecuteScalar().ToString();
/* use to pass the info to all the pages */
Session.Add("u_id", user_id);
}
}
根據文檔,您無法使用.ExecuteScalar()
訪問其他列:
執行查詢,返回查詢返回的結果集中第一行的第一列。 其他列或行將被忽略。
雖然這不是我推薦的路線,但您可以通過使用數據讀取器上的索引來遍歷字段:
SqlDataReader dataReader = cmd.ExecuteReader();
// for the query's result set, this while loop will go through all the records
while (dataReader.Read())
{
// for the current record, this for loop will go through all the fields
for (int i = 0; i < dataReader.FieldCount; i++)
{
var value = dataReader[i]; // do what you need with the data here
}
}
更好的方法是在 SQL 查詢中指定字段名稱而不是使用SELECT *
,然后通過特定字段名稱從數據讀取器獲取值(不依賴於數據庫中字段的順序)。
此外,您還有一個SQL 注入漏洞。 您應該查看這意味着什么以及如何參數化查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.