将值插入数据库时出现此错误。我已经在 SQL Sever Management Studio 中将身份规范属性设置为 ON,但我仍然面临这个错误。我也试过这种方式SET IDENTITY_INSERT Student ON
,在我的 SQL 命令中添加这一行,但它没有运行。
Default.aspx.cs
:
protected void btnsubmit_Click1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=INAFFFP1IT004W\MYSQL;Initial Catalog=test;User ID=sa;Password=test@1234;");
con.Open();
string SId = tbid.Text;
string FirstName = tbfirstname.Text;
string LastName = tblastname.Text;
string StartDate = tbstart.Text;
string EndDate = tbend.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into Student(SId,FirstName,LastName,StartDate,EndDate) values('" + SId + "','" + FirstName + "','" + LastName + "','" + StartDate + "','" + EndDate + "')";
cmd.Parameters.AddWithValue("@SId", tbid.Text);
cmd.Parameters.AddWithValue("@FirstName", tbfirstname.Text);
cmd.Parameters.AddWithValue("@LastName", tblastname.Text);
cmd.Parameters.AddWithValue("@StartDate", tbstart.Text);
cmd.Parameters.AddWithValue("@EndDate", tbend.Text);
cmd.ExecuteNonQuery();
}
con.Close();
tbid.Text = "";
tbfirstname.Text = "";
tblastname.Text = "";
tbstart.Text = "";
tbend.Text = "";
tbid.Focus();
}
**Default.aspx**:
<head runat="server">
<script type="text/javascript">
window.onload = function () {
new JsDatePick({
useMode: 2,
target: "tbstart",
dateFormat: "%M/%d/%Y"
});
new JsDatePick({
useMode: 2,
target: "tbend",
dateFormat: "%M/%d/%Y"
});
};
</script>
<title></title>
<style type="text/css">
.style1
{
width: 64px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<table cellpadding="2" cellspacing="5">
<tr>
<td>
<asp:Label ID="lblId" runat="server" Text="SId"></asp:Label>
</td>
<td>
<asp:TextBox ID="tbid" runat="server"></asp:TextBox>
</td>
<td class="style1">
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblname" runat="server" Text="FirstName"></asp:Label>
</td>
<td>
<asp:TextBox ID="tbfirstname" runat="server"></asp:TextBox>
</td>
<td class="style1">
</td>
</tr>
<tr>
<td>
<asp:Label ID="lbllastname" runat="server" Text="LastName"></asp:Label>
</td>
<td>
<asp:TextBox ID="tblastname" runat="server"></asp:TextBox>
</td>
<td class="style1">
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblstart" runat="server" Text="StartDate"></asp:Label>
</td>
<td>
<asp:TextBox ID="tbstart" runat="server"></asp:TextBox>
</td>
<td class="style1">
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblend" runat="server" Text="EndDate"></asp:Label>
</td>
<td>
<asp:TextBox ID="tbend" runat="server"></asp:TextBox>
</td>
<td class="style1">
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnupdate" runat="server" onclick="btnupdate_Click"
Text="Update" Width="63px" />
</td>
<td>
<asp:Button ID="btnsubmit" runat="server" Text="Submit"
onclick="btnsubmit_Click1" Width="102px" />
</td>
<td class="style1">
<asp:Button ID="btnsearch" runat="server" onclick="Button1_Click" Text="Search" />
</td>
</tr>
</table>
<br />
</form>
</body>