I am trying to learn asp.net and I am trying to add values to a database upon submission. After submission, I am getting an error message that says, "Must declare the scalar variable "@4". I am not sure what I am doing wrong and how to fix this error.
Below is my code
@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)";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.