Vikas

Vikas

  • 851
  • 831
  • 187.8k

After getting data through api, how to post in sql using c#

Mar 18 2020 4:19 AM
I have C# Console Application where I'm getting data from google-news-api and after that I want to post whole data to my sql server. So how is it possible 
  1. namespace ConsoleApp {  
  2.  class Program {  
  3.   static void Main(string[] args) {  
  4.    SqlConnection conn = new SqlConnection(@ "Server=SQLEXPRESS;Initial Catalog=testingnews;User Id=abctesting;Password=sabc;");  
  5.    conn.Open();  
  6.    SqlCommand cmd = new SqlCommand("insert into newstbl values ('50AE4E66-07C0-4AB0-936B-2778AFCB9787', '', '', '', '', '', '', '', '', '', '', '', 0, '', 0, '', 1, 0, '')", conn);  
  7.    SqlDataReader reader = cmd.ExecuteReader();  
  8.    while (reader.Read()) {  
  9.     Console.WriteLine("{0},{1}", reader.GetString(0), reader.GetString(1));  
  10.     Console.ReadLine();  
  11.    }  
  12.    reader.Close();  
  13.    conn.Close();  
  14.    try {  
  15.     GetNewsDetails().Wait();  
  16.    } catch (Exception ex) {}  
  17.   }  
  18.   
  19.   public static async Task < string > GetNewsDetails() {  
  20.    using(var _http = new HttpClient()) {  
  21.     _http.BaseAddress = new Uri("https://newsapi.org/v2/");  
  22.     _http.DefaultRequestHeaders.Clear();  
  23.     _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  24.     HttpResponseMessage response = await _http.GetAsync("everything?sources=&q=bbc-news&sortBy=publishedAt&pageSize=80&apiKey=4dbc17e007ab436fb66416009dfb59a8");  
  25.     response.EnsureSuccessStatusCode();  
  26.     using(HttpContent content = response.Content) {  
  27.      string responseBody = await content.ReadAsStringAsync();  
  28.      Console.WriteLine(responseBody);  // In responseBody I'm getting multiple data 
  29.      Console.ReadLine();  
  30.     }  
  31.    }  
  32.    return "objNewsRoot";  
  33.   }  
  34.   
  35.   
  36.  }  
  37. }  
 as per my logic some changes in line no 6 so please help me how to post array type data.

Answers (3)