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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈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…