【发布时间】:2021-04-02 11:19:30
【问题描述】:
我在 SQL Server 中创建了这个表来存储有关学生费用的数据:
create table Fee(
feeID int primary key identity(1,1),
classID int foreign key references Class(classID),
nameID int foreign key references Students(studentsID),
firstNameID int foreign key references Students(studentsID),
dateOfAdmission varchar(50),
monthKey int foreign key references Month(monthID), sum int
)
在 Visual Studio 中,我尝试使用以下方法将数据保存在表中:
private void btn_fee_Save_Click(object sender, EventArgs e)
{
int Class = Convert.ToInt32(cmbFeeClass.SelectedValue.ToString());
int Name = Convert.ToInt32(cmbFeeName.SelectedValue.ToString());
int firstName = Convert.ToInt32(cmbFeeFirstName.SelectedValue.ToString());
int Month = Convert.ToInt32(cmbMonth.SelectedValue.ToString());
try {
if (cmbFeeClass.Text != "" && cmbFeeName.Text != "" && cmbFeeFirstName.Text != "" && cmbMonth.Text != "" && txtSum.Text != "")
{
cmd = new SqlCommand("insert into Fee values('"+ Class + "', '" + Name + "', '" + firstName + "', " +
"'" + dtDateOfAdmission.Text + "', '" + Month + "', '" + "', '" + txtSum.Text + "')", con.ConnectionOpening());
cmd.ExecuteNonQuery();
MessageBox.Show("The data has been saved", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Please fill in all the fields!", "INFO", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.CloseConnection();
}
如何更改代码以使我不再出现此错误:
只有在使用列列表并且 IDENTITY_INSERT 为 ON 时,才能为表“Fee”中的标识列指定显式值
【问题讨论】:
-
1) 使用完整的
insert语法,在其中明确指定要插入的列(始终这样做的最佳做法)。 2) 使用SqlParameter's 传递数据,而不是连接字符串,这会让您对 SQL 注入敞开大门。 -
dateOfAdmission varchar(50),不 - 重新开始!
标签: c# sql sql-server visual-studio