Pontus Svedberg Pontus Svedberg - 6 days ago 5
SQL Question

SQL INSERT, trouble

Im trying to insert some data to my database in Webmatrix, I did it by a tutorial and then I tried to redo it on a second file to a second table in the same database and I just for my life cant seem to figure out why it does not work! I will post the code from the different cshtml files!

Also, the tables are pretty much identical, both with a primary key ID, then 3 columns all being nvarchar and same settings for everything, only difference being the name.

first file (the one that works)

@{
var getData = Database.Open("SmallBakery");
var Name = Request.Form["Name"];
var Description = Request.Form["Description"];
var Price = Request.Form["Price"];

if(IsPost && Validation.IsValid()){
if (ModelState.IsValid) {
var setData = "INSERT INTO Product (Name, Description, Price) " +
"VALUES (@0, @1, @2)";

getData.Execute(setData, Name, Description, Price);
Response.Redirect("~/ListProducts");
}
}
}


in body

<form method="post" action="">
<fieldset>
<legend>Add Product</legend>
<div>
<input placeholder="Name..." name="Name" type="text" size="50" value="@Name" />
</div>
<div>
<input placeholder="Description..." name="Description" type="text" size="50"
value="@Description" />
</div>
<div>
<input placeholder="Price..." name="Price" type="text" size="50" value="@Price" />
</div>
<div>
<label>&nbsp;</label>
<input type="submit" value="Insert" class="submit" />
</div>
</fieldset>
</form>


So the one above is the one that works!
The following does not work, ive been trying for hours to figure out why on earth is doesnt and would really like some help!

and the error im recieving is for this row:

getData.Execute(insertData, kg, set, rep);


.

{@
var getData = Database.Open("SmallBakery");
var Kg = Request.Form["Kg"];
var Set = Request.Form["Set"];
var Rep = Request.Form["Rep"];

if (IsPost && Validation.IsValid()) {
if (ModelState.IsValid) {
var insertData = "INSERT INTO Test (kg, set, rep) " +
"VALUES (@0, @1, @2)";

getData.Execute(insertData, kg, set, rep);
}
}
}


in body

<form method="post" action="">
<fieldset>
<legend>Add Product</legend>
<div>
<input placeholder="KG..." name="Kg" type="text" size="50" value="@Kg" />
</div>
<div>
<input placeholder="Number of sets..." name="Set" type="text" size="50" value="@Set" />
</div>
<div>
<input placeholder="Number of reps..." name="Rep" type="text" size="50" value="@Rep" />
</div>
<div>
<label>&nbsp;</label>
<input type="submit" value="Insert" class="submit" />
</div>
</fieldset>
</form>

Answer

The problem is that Set is a reserved word in MSSQL and many other databases and languages so try renaming the table column to something else and see if that works.

Comments