gpt4 book ai didi

c# - 在 C# 中使用函数按字段名称返回数据库值索引

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:00 26 4
gpt4 key购买 nike

我正在尝试使用函数从表中返回值,但我无法确定执行此操作的最佳方法。使用 SqlDataReader、字典、字符串数组?调用函数时,我需要使用字段名称字符串引用数据。

    public SqlDataReader staffInfo(string field, string Username)
{
string chk_PR = this.Is_PR_Staff(Username) == true ? BW_Config.default_postroom_staff : "";

string strDBConn = db.getDBstring(Globals.booDebug);
SqlConnection conn = new SqlConnection(strDBConn);

using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT " + field + " FROM BW_GetStaffInfo('" + Username + "', '" + chk_PR + "')";
cmd.Connection = conn;
conn.Open();

SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

if (reader.Read())
{
return reader;
}
else
{
return null;
}
}
}

使用函数:

SqlDataReader userInfo = User.staffInfo("StaffCode, GroupIDs, Perms", User.getUsername());

string staffCode = userInfo["StaffCode"].ToString());

它有效但奇怪的问题是它有时会永远循环..我想要一个类似的方法,它在做同样的事情,但它可以处理空值,并且如果可能的话,使用像字典或字符串数​​组这样的替代方法来有效地做到这一点?

谢谢

最佳答案

这个怎么样?我从我的 vb 代码改编而来,我不知道是否有语法错误,但你应该知道它的要点。 ;)

public Dictionary<String, Object> staffInfo(string field, string Username)
{
string chk_PR = this.Is_PR_Staff(Username) == true ? BW_Config.default_postroom_staff : "";

string strDBConn = db.getDBstring(Globals.booDebug);
SqlConnection conn = new SqlConnection(strDBConn);

using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT " + field + " FROM BW_GetStaffInfo('" + Username + "', '" + chk_PR + "')";
cmd.Connection = conn;
conn.Open();

SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

if (reader.Read())
{
Dictionary<String, Object> row = new Dictionary<String, Object>;
Object obj = nothing;
for (i = 0; i < reader.FieldCount; i++){
obj = reader.GetValue(i);
if (IsDBNull(obj)){
obj = "";
}
row.add(reader.GetName(i), obj);
}
return row;
}
else
{
return null;
}
}
}

关于c# - 在 C# 中使用函数按字段名称返回数据库值索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40302672/

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