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數據庫。根據實際需求,你可能需要添加更多的錯誤處理、日志記錄或配置管理功能。