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

解决方法

有几点需要更正:

  1. 指定SqlCommand类型

    myCommand.CommandType = CommandType.StoredProcedure;

  2. 添加参数

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

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

<!Doctype html>
<html>
<head>

<script type="text/javascript">
function validateDate(value) {
  var a = document.getElementById("date").value;
  if (a = = = "") {
    window.alert("Error");
    return false;
  }
}
</script>
</head>
<body>
<h1>Tee Time Sign-up Form</h1>
<form>
 <div id="teeDate">
      Date:<input type=“date” id=“date” name=“date”><br>
     <button id=teeTime onClick="validateDate()">Submit</button><br>
</div>
</form>
</body>
</html>

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...