更新 .net 核心控制台应用程序列中的所有空值

Update all null values in column .netcore console app

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

我不确定我是否应该基于所有空 instagramId 创建一个假的 table 然后使用它们来更新我的专栏,或者是否有另一种更简洁的方法。此控制台应用程序仅供一次性使用,因此只需快速修复即可。

  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}");
                }
            }
        }
    }
}

这里好像有两个问题

  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)