C# POST请求与MySQL数据存储实现
下面是一个完整的C#解决方案,用于发送POST请求、接收响应数据,并将数据保存到MySQL数据库中。
完整代码实现
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using MySql.Data.MySqlClient;
using System.Collections.Generic;
// 请求数据模型
public class RequestData
{
public string CompanyId { get; set; }
public string ApiName { get; set; }
public ProductRequest[] Data { get; set; }
}
public class ProductRequest
{
public string NestingId { get; set; }
public string AutoType { get; set; }
}
// 响应数据模型
public class ResponseData
{
public string Code { get; set; }
public string Message { get; set; }
public List<ProductData> Data { get; set; }
}
public class ProductData
{
public string ShipCode { get; set; }
public string SerialNumber { get; set; }
public string DrawingCode { get; set; }
public string ProcessSeries { get; set; }
public int PipeSegmentCode { get; set; }
public int Caliber { get; set; }
public int Thickness { get; set; }
public string Material { get; set; }
public int CuttingLength { get; set; }
public string BendingDie { get; set; }
public string FirstEnd { get; set; }
public string FinalEnd { get; set; }
public string FirstEndCorner { get; set; }
public string FinalEndCorner { get; set; }
public int BendSeq { get; set; }
public string BendY { get; set; }
public string BendB { get; set; }
public string BendC { get; set; }
public string PipeDepth { get; set; }
public string BendType { get; set; }
public string NestingId { get; set; }
public string NestingDate { get; set; }
public string LotId { get; set; }
}
public class DataService
{
private readonly string _connectionString;
public DataService(string connectionString)
{
_connectionString = connectionString;
}
// 发送POST请求并获取响应
public async Task<ResponseData> GetProductDataAsync()
{
// 请求参数
var requestBody = new RequestData
{
CompanyId = "8010",
ApiName = "QUERYPRODUCTDATA",
Data = new[]
{
new ProductRequest
{
NestingId = "202507001",
AutoType = "1"
}
}
};
using (var client = new HttpClient())
{
// 序列化请求数据
string json = JsonConvert.SerializeObject(requestBody);
var content = new StringContent(json, Encoding.UTF8, "application/json");
// 发送POST请求
HttpResponseMessage response = await client.PostAsync("http://172.30.0.43:18086/common/postrequest", content);
// 确保成功响应
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseContent = await response.Content.ReadAsStringAsync();
// 反序列化响应
return JsonConvert.DeserializeObject<ResponseData>(responseContent);
}
}
// 保存数据到MySQL数据库
public async Task SaveProductDataToDatabase(List<ProductData> productDataList)
{
using (var connection = new MySqlConnection(_connectionString))
{
await connection.OpenAsync();
foreach (var product in productDataList)
{
// 使用参数化查询防止SQL注入
var query = @"INSERT INTO product (
ship_code, serial_number, drawing_code, process_series,
pipe_segment_code, caliber, thickness, material, cutting_length,
bending_die, first_end, final_end, first_end_corner, final_end_corner,
bend_seq, bend_y, bend_b, bend_c, pipe_depth, bend_type,
nesting_id, nesting_date, lot_id
) VALUES (
@ShipCode, @SerialNumber, @DrawingCode, @ProcessSeries,
@PipeSegmentCode, @Caliber, @Thickness, @Material, @CuttingLength,
@BendingDie, @FirstEnd, @FinalEnd, @FirstEndCorner, @FinalEndCorner,
@BendSeq, @BendY, @BendB, @BendC, @PipeDepth, @BendType,
@NestingId, @NestingDate, @LotId
)";
using (var command = new MySqlCommand(query, connection))
{
// 添加参数
command.Parameters.AddWithValue("@ShipCode", product.ShipCode);
command.Parameters.AddWithValue("@SerialNumber", product.SerialNumber);
command.Parameters.AddWithValue("@DrawingCode", product.DrawingCode);
command.Parameters.AddWithValue("@ProcessSeries", product.ProcessSeries);
command.Parameters.AddWithValue("@PipeSegmentCode", product.PipeSegmentCode);
command.Parameters.AddWithValue("@Caliber", product.Caliber);
command.Parameters.AddWithValue("@Thickness", product.Thickness);
command.Parameters.AddWithValue("@Material", product.Material);
command.Parameters.AddWithValue("@CuttingLength", product.CuttingLength);
command.Parameters.AddWithValue("@BendingDie", product.BendingDie);
command.Parameters.AddWithValue("@FirstEnd", product.FirstEnd);
command.Parameters.AddWithValue("@FinalEnd", product.FinalEnd);
command.Parameters.AddWithValue("@FirstEndCorner", product.FirstEndCorner);
command.Parameters.AddWithValue("@FinalEndCorner", product.FinalEndCorner);
command.Parameters.AddWithValue("@BendSeq", product.BendSeq);
command.Parameters.AddWithValue("@BendY", product.BendY);
command.Parameters.AddWithValue("@BendB", product.BendB);
command.Parameters.AddWithValue("@BendC", product.BendC);
command.Parameters.AddWithValue("@PipeDepth", product.PipeDepth);
command.Parameters.AddWithValue("@BendType", product.BendType);
command.Parameters.AddWithValue("@NestingId", product.NestingId);
command.Parameters.AddWithValue("@NestingDate", product.NestingDate);
command.Parameters.AddWithValue("@LotId", product.LotId);
await command.ExecuteNonQueryAsync();
}
}
}
}
}
public class Program
{
static async Task Main(string[] args)
{
// MySQL连接字符串 - 请根据实际情况修改
string connectionString = "server=localhost;database=your_database;uid=username;pwd=password;";
var dataService = new DataService(connectionString);
try
{
// 获取数据
Console.WriteLine("正在从服务器获取数据...");
var response = await dataService.GetProductDataAsync();
if (response.Code == "200")
{
Console.WriteLine("数据获取成功,正在保存到数据库...");
// 保存到数据库
await dataService.SaveProductDataToDatabase(response.Data);
Console.WriteLine($"成功保存 {response.Data.Count} 条记录到数据库。");
}
else
{
Console.WriteLine($"请求失败: {response.Message}");
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
}
```
## MySQL表结构
在运行代码之前,需要先创建MySQL数据库表。以下是创建product表的SQL语句:
```sql
CREATE TABLE product (
id INT AUTO_INCREMENT PRIMARY KEY,
ship_code VARCHAR(50),
serial_number VARCHAR(50),
drawing_code VARCHAR(50),
process_series VARCHAR(10),
pipe_segment_code INT,
caliber INT,
thickness INT,
material VARCHAR(50),
cutting_length INT,
bending_die VARCHAR(50),
first_end VARCHAR(10),
final_end VARCHAR(10),
first_end_corner VARCHAR(10),
final_end_corner VARCHAR(10),
bend_seq INT,
bend_y VARCHAR(10),
bend_b VARCHAR(10),
bend_c VARCHAR(10),
pipe_depth VARCHAR(10),
bend_type VARCHAR(50),
nesting_id VARCHAR(50),
nesting_date DATE,
lot_id VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
## 安装必要的NuGet包
在运行代码前,需要通过NuGet安装以下包:
```
Install-Package Newtonsoft.Json
Install-Package MySql.Data
Install-Package System.Net.Http
```
代码说明
1. 数据模型:
- 定义了请求和响应的数据模型类,与JSON结构对应
- 使用JsonProperty特性处理可能的命名差异
2. HTTP请求:
- 使用HttpClient发送POST请求
- 设置正确的Content-Type头
- 处理异步操作和错误
3. 数据库操作:
- 使用MySQL Connector/NET进行数据库操作
- 参数化查询防止SQL注入
- 支持批量插入数据
4. 错误处理:
- 包含基本的异常处理
- 检查HTTP响应状态码
- 检查API返回的业务状态码
使用说明
1. 修改MySQL连接字符串以匹配你的数据库配置
2. 确保MySQL数据库中已创建product表
3. 运行程序,它将自动获取数据并保存到数据库
这个实现提供了完整的端到端解决方案,从发送HTTP请求到将数据持久化到MySQL数据库。根据实际需求,你可能需要添加更多的错误处理、日志记录或配置管理功能。