C#實現通過POST實現讀取數據

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/922401.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/922401.shtml
英文地址,請注明出處:http://en.pswp.cn/news/922401.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java 字符編碼問題,怎么優雅地解決?

網羅開發&#xff08;小紅書、快手、視頻號同名&#xff09;大家好&#xff0c;我是 展菲&#xff0c;目前在上市企業從事人工智能項目研發管理工作&#xff0c;平時熱衷于分享各種編程領域的軟硬技能知識以及前沿技術&#xff0c;包括iOS、前端、Harmony OS、Java、Python等方…

STL之string類(C++)

1.string類核心定位std::string 本質是對 “字符序列” 的封裝&#xff0c;內部通過動態數組存儲字符&#xff0c;并自動管理內存&#xff08;分配、擴容、釋放&#xff09;&#xff0c;對外提供了簡潔的接口用于字符串的創建、修改、拼接、查找等操作。1.1 使用前提頭文件包含…

[Maven 基礎課程]第一個 Maven 項目

idea 新建一個項目&#xff1a; 來到 New Project 頁面&#xff1a; 這里我們有兩種方式創建 maven 項目&#xff0c;一種是自定義創建&#xff0c;另一種是使用 maven 模版項目創建。 自定義創建 maven 項目 基本配置 Name: first_maven_project 項目名稱&#xff0c;設為 …

uni小程序中使用Echarts圖表

前言 今天雞米花給大家帶來的是在uni里面使用echarts&#xff0c;能夠完美支持和PC端一樣的效果&#xff0c;我這邊的工程是uni轉為微信小程序&#xff0c;用的是vue3vite來寫的&#xff0c;然后實現了豎屏和橫屏的展示方式&#xff0c;好了獻上效果圖。 效果圖 一、引入插件 這…

從FOTA測試到汽車電子安全體系的啟蒙之旅

我是穿拖鞋的漢子,魔都中堅持長期主義的汽車電子工程師。 老規矩,分享一段喜歡的文字,避免自己成為高知識低文化的工程師: 做到欲望極簡,了解自己的真實欲望,不受外在潮流的影響,不盲從,不跟風。把自己的精力全部用在自己。一是去掉多余,凡事找規律,基礎是誠信;二是…

stm32中 中斷和事件的區別

一、核心概念比喻想象一下工廠里的一個報警系統&#xff1a;?中斷 (Interrupt)??&#xff1a;就像火警警報器響了。它的目的是通知管理員&#xff08;CPU&#xff09;??&#xff1a;“著火了&#xff01;”。管理員聽到后&#xff0c;會停下手中的工作&#xff08;保存現場…

深入理解MySQL主從架構中的Seconds_Behind_Master指標

問題&#xff1a;主從延遲與寫后讀不一致 在典型的 MySQL 主從架構下&#xff0c;所有寫操作都會直接進入主庫&#xff0c;而讀操作大多分流到從庫&#xff0c;從而實現讀寫分離&#xff0c;緩解主庫壓力。 然而 MySQL 的復制機制是異步的&#xff1a;主庫先寫入 binlog&#…

MySQL安裝(linux版本)

MySQL安裝&#xff08;linux版本&#xff09; 課程地址 08. 進階-MySQL安裝(linux版本)_嗶哩嗶哩_bilibili 安裝過程中所有需要的程序都放在網盤里了 通過網盤分享的文件&#xff1a;虛擬機 鏈接: https://pan.baidu.com/s/1eLMD2iq1uEujNN7mWs2dIg?pwdckmh 提取碼: ckmh …

OpenCV 圖像雙三次BSpline插值

文章目錄 一、簡介 二、實現代碼 三、實現效果 參考資料 一、簡介 之前我們介紹過BSpline曲線,一條B樣條曲線可以被定義成 n + 1 n+1 n+1個控制點的集合 { Q i } i = 0 n {\{Q_i\}}^{n}_{i=0}

Prometheus+Grafana構建企業級監控方案

1.prometheus工作原理&#xff1a; Prometheus將指標收集并存儲為時間序列數據庫&#xff08;時序數據庫&#xff09;&#xff0c;即指標信息與記錄它的時間戳一起存儲&#xff0c;以及稱為標簽的可選鍵值對。 特性&#xff1a; 具有由指標名稱和鍵/值對識別的時間序列數據的…

第23課:行業解決方案設計

第23課:行業解決方案設計 課程目標 掌握金融、醫療、教育等行業應用 學習領域特定Agent設計 了解行業標準集成 實踐設計行業解決方案 課程內容 23.1 金融行業解決方案 金融Agent系統 class FinancialAgentSystem {constructor() {this.agents =

Go語言快速入門教程(JAVA轉go)——2 環境搭建與入門

安裝go Go官網下載地址&#xff1a;https://golang.org/dl/ 中國區官方鏡像站&#xff08;推薦&#xff09;&#xff1a;https://golang.google.cn/dl/ windows安裝 下載好后選擇安裝路徑即可&#xff0c;安裝完成后&#xff0c;winr 輸入cmd調出命令行窗口&#xff0c;輸入…

ffplay播放pcm

用 ffplay 播放 PCM 裸流時&#xff0c;必須手動告訴它“沒有封裝頭、采樣率、聲道數、采樣格式”四個關鍵點。命令模板如下&#xff1a; ffplay -f <采樣格式> -ar <采樣率> -ac <聲道數> -i <pcm文件>常用組合示例 48 kHz、16 bit、小端、雙聲道 ffp…

【LLM】大模型訓練中的穩定性問題

訓練穩定性問題 &#x1f4cb; 概述 本文檔詳細介紹了在項目中解決訓練穩定性問題的方法、原理分析以及實際應用。涵蓋了梯度裁剪、損失函數優化、數值穩定化處理和學習率調度等關鍵技術。&#x1f6a8; 問題描述 現象: 訓練過程中出現數值不穩定&#xff0c;損失函數波動劇烈 …

【linux系統】6. 基礎開發工具(一)

一. 軟件包管理器 1&#xff09;Linux下安裝軟件的常用方法 1. 源代碼安裝 下載程序的源代碼&#xff0c;本地編譯成二進制文件&#xff0c;拷貝到系統指定路徑下。 2. rpm包安裝 已經編譯好的安裝包&#xff0c;使用rpm對應的指令去安裝&#xff0c;也比較麻煩。 3. 包…

ffplay數據結構分析

struct VideoState 播放器封裝 typedef struct VideoState {SDL_Thread *read_tid; // 讀線程句柄AVInputFormat *iformat; // 指向demuxerint abort_request; // 1時請求退出播放int force_refresh; // 1時刷新畫面&#xff0c;請求立即刷新畫面的意思int paused; …

OpenCV:銀行卡號識別

目錄 一、項目原理與核心技術 二、環境準備與工具包導入 1. 環境依賴 2. 工具包導入 三、自定義工具類 myutils.py 實現 四、主程序核心流程&#xff08;銀行卡識別.py&#xff09; 1. 命令行參數設置 2. 銀行卡類型映射 3. 輔助函數&#xff1a;圖像展示 五、步驟 1…

基于spark的澳洲光伏發電站選址預測

基于spark的澳洲光伏發電站選址預測項目概況 [&#x1f447;&#x1f447;&#x1f447;&#x1f447;&#x1f447;&#x1f447;&#x1f447;&#x1f447;] 點這里,查看所有項目 [&#x1f446;&#x1f446;&#x1f446;&#x1f446;&#x1f446;&#x1f446;&#x…

Kibana 雙棧網絡(Dual-Stack)支持能力評估

#作者&#xff1a;Unstopabler 文章目錄一&#xff0e;測試目標二&#xff0e;測試環境三&#xff0e;Kibana1、查詢 Kibana pod信息2、查詢Kibana service信息3、Kibana service 設置四&#xff0e;驗證測試1、Kibana 監聽參數設置2、Kibana節點IPv4狀態檢查3、Kibana節點IPv6…

標準CAN幀介紹

標準CAN幀介紹標準CAN&#xff08;Controller Area Network&#xff09;結構1.幀起始&#xff08;SOF-Start Of Frame&#xff09;2.仲裁段&#xff08;Arbitration Field&#xff09;3.控制段&#xff08;Control Field&#xff09;4.數據段&#xff08;Data Field&#xff09…