[英]ASP.NET MVC and WebAPI inserting and retriveing records with database table
[英]asp.net inserting records into a database
我正在嘗試學習 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>
更改您的 SQL 命令參數,以 0 索引開始:
var q2 = "INSERT INTO CartItems (PID, PName, UnitPrice, Quantity) VALUES (@0, @1, @2, @3)";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.