c# 做个1分钟定时执行将sql语句查询type=2 的值循环插入json{"a":"a","b":[{"c":"c","d":"d"},{"c":"c","d":"d"}] }发送post请求,得到返回值json{"aa":"aa"},根据返回修改type=3
时间: 2023-11-05 13:06:08 浏览: 244
一条SQL查询语句是如何执行的
您可以按照以下步骤来实现您的需求:
1. 使用C#中的定时器Timer,设置定时器的时间间隔为1分钟,然后在定时器的Elapsed事件中编写查询type=2的SQL语句并将结果循环插入到一个List中。
2. 使用Newtonsoft.Json库将List转换为JSON字符串,然后发送POST请求并获取返回值。
3. 使用Newtonsoft.Json库将返回值JSON字符串转换为对象,然后修改其中type=3的值。
4. 将修改后的对象转换为JSON字符串,然后发送POST请求并获取返回值。
下面是示例代码:
```
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Net.Http;
using Newtonsoft.Json;
public class Program
{
private static Timer _timer;
public static void Main()
{
_timer = new Timer(60000); // 1分钟
_timer.Elapsed += OnTimerElapsed;
_timer.Start();
Console.ReadLine();
}
private static void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
var list = new List<object>();
using (var connection = new SqlConnection("your_connection_string"))
{
connection.Open();
using (var command = new SqlCommand("SELECT * FROM your_table WHERE type = 2", connection))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var obj = new
{
c = reader.GetString(reader.GetOrdinal("c")),
d = reader.GetString(reader.GetOrdinal("d"))
};
list.Add(obj);
}
}
}
}
var json = JsonConvert.SerializeObject(new { a = "a", b = list });
using (var client = new HttpClient())
{
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = client.PostAsync("your_url", content).Result;
var responseJson = response.Content.ReadAsStringAsync().Result;
var responseObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseJson);
if (responseObj.ContainsKey("aa"))
{
var aa = responseObj["aa"];
var obj = JsonConvert.DeserializeObject<dynamic>(json);
foreach (var item in obj.b)
{
if (item.c == "c" && item.d == "d")
{
item.type = 3;
}
}
var modifiedJson = JsonConvert.SerializeObject(obj);
var modifiedContent = new StringContent(modifiedJson, Encoding.UTF8, "application/json");
var modifiedResponse = client.PostAsync("your_url", modifiedContent).Result;
var modifiedResponseJson = modifiedResponse.Content.ReadAsStringAsync().Result;
}
}
}
}
```
阅读全文