asp.net - SQL 存储过程和 ASP.NET API 控制器
问题描述
我正在尝试为我的删除方法编写一个存储过程。它适用于我创建的字符串查询,但我正在努力使其更安全。这是我改变之前的情况。
存储过程 控制器之前
[HttpDelete]
public JsonResult Delete(int ID)
{
string query = @"DELETE FROM dbo.WeatherForecast WHERE ID =" + ID;
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("WeatherAppCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (System.Data.SqlClient.SqlCommand myCommand = new SqlCommand(query, myCon))
{
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult("Row Deleted Successfully");
}
存储过程 控制器之后
[HttpDelete]
public JsonResult Delete(int ID)
{
string query = "dbo.p_WeatherForecastDelete";
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("WeatherAppCon");
SqlDataReader myReader;
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (System.Data.SqlClient.SqlCommand myCommand = new SqlCommand(query, myCon))
{
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
myCon.Close();
}
}
return new JsonResult("Row Deleted Successfully");
}
SQL 存储过程(不起作用)
USE [WeatherTemplate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[p_WeatherForecastDelete]
AS
BEGIN
DELETE FROM dbo.WeatherForecast WHERE ID = + ID;
END
解决方案
有几点需要纠正:
指定 SqlCommand 类型
myCommand.CommandType = CommandType.StoredProcedure;
添加参数
myCommand.Parameters.Add(new SqlParameter("@ID", ID));
修复存储过程以接收参数并正确使用它
ALTER PROCEDURE [dbo].[p_WeatherForecastDelete]
@ID INT
AS
BEGIN
DELETE FROM dbo.WeatherForecast WHERE ID = @ID;
END
您似乎也没有阅读执行结果,因此您可以安全地将 myCommand.ExecuteReader() 替换为 myCommand.ExecuteNonQuery()
推荐阅读
- pine-script - 松树脚本中的 VWAP
- api - 使用 OAuth 2.0 使用可变令牌进行 API 调用
- c++ - 在运行时有条件地删除类成员或跳过调用该成员对象的构造函数
- python - Pandas DataFrame 根据多个条件分组添加新列值
- java - Spring核心:为@Bean方法使用接口结果类型
- python - 来自 HTMLParser 的 Python 可覆盖函数
- webpack - 强制纱线将某些模块安装到给定的工作区,而不是将它们移动到monorepo的共享节点模块?
- tensorflow - 大型数据集的多标签损失函数
- php - 路线 [删除博客] 未定义。(查看:C:\xampp\htdocs\laravel\resources\views\blogs\blog.blade.php)错误
- ios - 不可访问时,UserDefaults 是否返回默认值或 nil?