问题描述
我正在尝试为我的删除方法编写一个存储过程。它适用于我创建的字符串查询,但我正在努力使其更安全。这是我改变之前的样子。
在存储过程之前 控制器
[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));
-
修复存储过程以接收参数并正确使用
<!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()