我正在尝试学习asp.net,并且试图在提交后向数据库添加值。提交后,我收到一条错误消息:“必须声明标量变量“ @ 4”。我不确定自己在做什么以及如何解决此错误。
下面是我的代码
@using WebMatrix.Data;
@{
var db = Database.Open("Database");
var commandText = "SELECT * FROM ShoppingCartData";
var pid = 1111;
var pname = "Hangover";
var unitprice = 23.54;
var quantity = 1;
if (IsPost)
{
var q2 = "INSERT INTO CartItems (PID, PName, UnitPrice, Quantity) VALUES (@1, @2, @3, @4)";
db.Execute(q2, pid, pname, unitprice, quantity);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add to database</title>
<meta charset="utf-8" />
<style type="text/css">
body {
background-color: beige;
font-family: Verdana, Arial;
margin: 50px;
}
form {
padding: 10px;
border-style: solid;
width: 250px;
}
</style>
</head>
<body>
<form action="" method="post">
<p>
Add entry to database
<p><input type="submit" value="Add" /></p>
</form>
<table>
<caption>Print out newly added row</caption>
<tr>
<th>Id</th>
<th>Product</th>
<th>Description</th>
<th>Price</th>
</tr>
@foreach (var row in db.Query(commandText))
{
<tr>
<td>@row.PID</td>
<td>@row.PName</td>
<td>@row.UnitPrice</td>
<td>@row.Quantity</td>
</tr>
}
</table>
</body>
</html>
答案 0 :(得分:1)
更改SQL命令参数,以0索引开头:
var q2 = "INSERT INTO CartItems (PID, PName, UnitPrice, Quantity) VALUES (@0, @1, @2, @3)";