本文共 3416 字,大约阅读时间需要 11 分钟。
在这个示例中,我们将使用Dapper框架来执行数据库查询操作。以下是查询操作的实现步骤:
确保在代码文件中包含以下命名空间引用:
using Dapper;using Microsoft.AspNetCore.Mvc;using Newtonsoft.Json;using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;using System.Linq;using System.Security.Cryptography;using System.Text.Json;using System.Threading.Tasks;using TP.Domain;using TP.Infrastructure;using TPAPI.ModelsVue;创建一个新的控制器类,继承自Controller类,并添加以下特性:
[Route("api/[controller]")][ApiController][ApiExplorerSettings(GroupName = "yw")]public class SqlController : Controller{ // 其他方法...} 以下是查询操作的实现代码:
[HttpPost("/[controller]/testSelselect")]public string testSelselect(string person){ try { using (SqlConnection connection = new SqlConnection(TPConfig.conn_Main)) { connection.Open(); string sql = "SELECT * FROM testTable where person=@person"; var resClassSet = connection.Query(sql, new { person = person }).ToList(); return JsonConvert.SerializeObject(resClassSet); } } catch (Exception) { throw; }} 在代码中,connection.Query方法用于执行SQL查询,@person参数将传递到数据库中。返回结果通过JsonConvert.SerializeObject转换为JSON格式。
接下来,我们将实现CRUD(创建、读取、更新、删除)操作,分别对应于testInsert、testDelete、testUpdate方法。
以下是插入操作的实现代码:
[HttpPost("/[controller]/testInsert")]public string testInsert([FromBody] object data){ try { using (SqlConnection connection = new SqlConnection(TPConfig.conn_Main)) { connection.Open(); var result = (JObject)JsonConvert.DeserializeObject(data.ToString()); string sql = "insert into testTable (code,name,person) values (@code,@name,@person)"; connection.Execute(sql, new { code = result["code"].ToString(), name = result["name"].ToString(), person = result["person"].ToString() }); return "OK!"; } } catch (Exception) { throw; }} 以下是删除操作的实现代码:
[HttpPost("/[controller]/testDelete")]public string testDelete([FromBody] object data){ try { using (SqlConnection connection = new SqlConnection(TPConfig.conn_Main)) { connection.Open(); var result = (JObject)JsonConvert.DeserializeObject(data.ToString()); string sql = "delete from testTable where Id=@id"; connection.Execute(sql, new { id = result["id"].ToString() }); return "OK!"; } } catch (Exception) { throw; }} 以下是更新操作的实现代码:
[HttpPost("/[controller]/testUpdate")]public string testUpdate([FromBody] object data){ try { using (SqlConnection connection = new SqlConnection(TPConfig.conn_Main)) { connection.Open(); var result = (JObject)JsonConvert.DeserializeObject(data.ToString()); string sql = "update testTable set name=@name where ID=@Id"; connection.Execute(sql, new { name = result["name"].ToString(), Id = result["Id"].ToString() }); return "OK!"; } } catch (Exception) { throw; }} 在以上方法中,我们使用了[FromBody] object data来接收来自客户端的数据。为了确保数据的安全性和完整性,可以在处理数据之前进行参数验证和过滤。
每个方法都包含了try-catch块,以确保在发生异常时能够及时捕获并抛出错误信息。
通过以上实现,可以轻松地使用Dapper框架对SQL数据库进行CRUD操作,并将结果返回给客户端。
转载地址:http://pkvp.baihongyu.com/