SQL 存储过程和 ASP.NET API 控制器

SQL Stored Procedure and ASP.NET API Controller

我正在尝试为我的删除方法编写一个存储过程。它适用于我创建的字符串查询,但我试图让它更安全。这是我更改之前的内容。

存储过程之前 控制器

[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

有几处需要更正:

  1. 指定 SqlCommand 类型

    myCommand.CommandType = CommandType.StoredProcedure;

  2. 添加参数

    myCommand.Parameters.Add(new SqlParameter("@ID", ID));

  3. 修复存储过程以接收参数并正确使用它

    ALTER PROCEDURE [dbo].[p_WeatherForecastDelete]
        @ID INT
    AS
    BEGIN
        DELETE FROM dbo.WeatherForecast WHERE ID = @ID;
    END

您似乎也没有读取执行结果,因此您可以安全地将 myCommand.ExecuteReader() 替换为 myCommand.ExecuteNonQuery()