You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何将数据库查询到的指定数据存储到字符串数组中

解决方案

你现有代码存在两处核心问题:

  1. 方法声明返回值为string[],但现有逻辑中返回的是reader["properties"].ToString()的单个字符串,类型不匹配
  2. 没有对存储的逗号分隔属性字段做拆分处理

修正后完整代码

public static string[] SelectData(string data)
{
    SqlConnection connection = Connection();
    // 原switch判断连接是否为空的写法可简化为直接判空
    if (connection == null)
    {
        return null;
    }
    try
    {
        // 原代码这里漏掉了分号,已补充
        var cmd = "SELECT command, properties FROM ai WHERE command = @command";
        using (SqlCommand command = new SqlCommand(cmd, connection))
        {
            command.Parameters.AddWithValue("@command", data);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                if (reader.Read())
                {
                    // 先读取属性字段值,判空后按逗号拆分
                    string propertiesStr = reader["properties"]?.ToString();
                    if (string.IsNullOrEmpty(propertiesStr))
                    {
                        return Array.Empty<string>();
                    }
                    // 按英文逗号拆分得到字符串数组,可选参数可按需开启
                    return propertiesStr.Split(',', 
                        StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
                }
                return null;
            }
        }
    }
    finally
    {
        // 统一在finally块关闭连接,避免异常时连接泄漏
        connection.Close();
    }
}

核心逻辑说明

  • 从数据库读取的properties字段是英文逗号分隔的字符串,直接调用Split(',')方法即可按逗号拆分得到符合要求的字符串数组
  • 可按需配置StringSplitOptions参数:
    • TrimEntries:自动去除每个属性值前后的空白字符
    • RemoveEmptyEntries:自动过滤拆分得到的空字符串,避免字段首尾有逗号时生成空元素

内容的提问来源于stack exchange,提问作者Bradley Methorst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:48:05