【问题标题】:Update all null values in column .netcore console app更新列 .net 核心控制台应用程序中的所有空值
【发布时间】:2020-10-04 21:29:42
【问题描述】:

我有一个控制台应用程序,它根据用户输入更新数据库中名为 InstagramId 的列。我希望能够查询数据库,如果有一个为空的 instagramId,则根据他们的 instagramUsername 使用正确的 instagramID 更新它。

我不确定是否应该根据所有 null instagramId 创建一个假表,然后使用它们来更新我的列,或者是否有另一种更简洁的方法。此控制台应用程序只能使用一次,因此只需快速修复即可。

  class Program
    {
        static async Task Main(string[] args)
        {
            // receive a profile name
            var tasks = new List<Task<InstagramUser>>();
            foreach (var arg in args)
            {
                if (string.IsNullOrEmpty(arg)) continue;
                var profileName = arg;
                var url = $"https://instagram.com/{profileName}";
                tasks.Add(ScrapeInstagram(url));
            }

            try
            {
                var instagramUsers = await Task.WhenAll<InstagramUser>(tasks);
                foreach (var iu in instagramUsers)
                {
                    iu.Display();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

        }


        public static async Task<InstagramUser> ScrapeInstagram(string url)
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    // create html document
                    var htmlBody = await response.Content.ReadAsStringAsync();
                    var htmlDocument = new HtmlDocument();
                    htmlDocument.LoadHtml(htmlBody);

                    // select script tags
                    var scripts = htmlDocument.DocumentNode.SelectNodes("/html/body/script");

                    // preprocess result
                    var uselessString = "window._sharedData = ";
                    var scriptInnerText = scripts[0].InnerText
                        .Substring(uselessString.Length)
                        .Replace(";", "");

                    // serialize objects and fetch the user data
                    dynamic jsonStuff = JObject.Parse(scriptInnerText);
                    dynamic userProfile = jsonStuff["entry_data"]["ProfilePage"][0]["graphql"]["user"];

                    //Update database query 
                    string connectionString = @"Server=mockup-dev-db";


                    using (SqlConnection con = new SqlConnection(connectionString))
                    {
                        SqlCommand cmd = new SqlCommand("Update ApplicationUser Set InstagramId = '" + userProfile.id + "'" + "where Instagram =  '" + userProfile.username + "'", con);
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();

                    }

                    // create an InstagramUser
                    var instagramUser = new InstagramUser
                    {
                        FullName = userProfile.full_name,
                        FollowerCount = userProfile.edge_followed_by.count,
                        FollowingCount = userProfile.edge_follow.count,
                        Id = userProfile.id,
                        url = url
                    };
                    return instagramUser;
                }
                else
                {
                    throw new Exception($"Something wrong happened {response.StatusCode} - {response.ReasonPhrase} - {response.RequestMessage}");
                }
            }
        }
    }
}

【问题讨论】:

  • 您当前的解决方案有什么问题?简短的外观表明它应该可以正常工作。
  • 它目前仅在一次搜索一个时才有效。例如。我将运行调试文件并拥有用户名 (test.nora),它会更新该用户的 InstagramID。我没有查询我正在搜索数据库然后更新所有空 InstagramID 值

标签: c# sql asp.net-core console-application


【解决方案1】:

这里好像有两个问题

  1. 从数据库中检索具有空 instagram ID 的用户名列表
  2. 对于其中的每一个,下载并填充 instagram ID

看起来你已经解决了 1,那么我们来看看数字 2:

可以使用 SQL 查询获取此数据:

SELECT Instagram FROM ApplicationUser WHERE InstagramId IS NULL

在 C# 中可能如下所示:

using (SqlConnection con = new SqlConnection(connectionString))
    {
    SqlCommand cmd = new SqlCommand("SELECT Instagram FROM ApplicationUser WHERE InstagramId IS NULL", con);
cmd.Connection.Open();
    var instagramUsernames = new List<string>();

    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        instagramUsernames.Add(reader.GetString(0));
    }
}

现在您拥有instagramUsernames 列表中的所有用户名,并且可以在 foreach 循环中执行现有代码(稍作修改)。

您现在将遍历 instagramUsernames 列表,而不是遍历 args(因此上面的代码将出现在 Main 方法的开头): foreach (var arg in args) 会变成foreach (var arg in instagramUsernames)

【讨论】:

  • 我要改成什么? // 接收个人资料名称 var tasks = new List>(); foreach (var arg in args) { if (string.IsNullOrEmpty(arg)) 继续; var profileName = arg; var url = $"instagram.com{profileName}"; ta
  • 因为目前我在运行控制台应用程序时必须输入用户名
  • 请看我的编辑。此外,您还需要进行重构和整理。
  • 这将保持不变:在您循环通过args 的那一刻,得到一个单独的arg,它变成了profileName。现在不是循环通过args,而是循环通过从数据库返回的instagramUsernames
  • 这一行出现类型错误 - instagramUsernames.Add(reader[0]);不让我将 obj 转换为字符串。我也尝试过申请铸造,但没有运气
猜你喜欢
  • 1970-01-01
  • 2019-09-26
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多