您好,我正在处理一个具有简单表格和数据库的学校作业。
数据库中有学生表。
问题:
当我输入stu_ID作为整数(它是主键,例如1234)时,此程序有效 当我输入stu_ID为非整数时会出现问题。(分配要求)。 像BSCS-122一样,它也会出现以下异常情况
'System.Data.SqlClient.SqlException' {"Invalid column name 'BSCS'."}
我正在使用Visual Studio 2015 SQL Server 2008 R2 Express。
students stu_Id varchar(50) PK stu_Name varchar(50) Stu_Age int stu_Semester int stu_City varchar(50) +------------+-----------------+---------+--------------+-------------+ | stu_Id | stu_Name | Stu_Age | stu_Semester | stu_City | +------------+-----------------+---------+--------------+-------------+ | BSCS-122 | Danish Kareem | 22 | 5 | Decya | | MBA-233 | Kamran | 23 | 5 | JPT | | .. .... | ............... | ..... ..| ....... .....| ...... .....| +------------+-----------------+---------+--------------+-------------+
下面是C#代码。
private void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection objSqlConnection = new SqlConnection(@"Data Source=DESKTOP-VESS66M\SQLEXPRESS;Initial Catalog=Persons;Integrated Security=True");
try
{
//
objSqlConnection.Open();
string insertCommand = "INSERT INTO students VALUES (" +stu_ID.Text+ ",'" + stu_Name.Text + "','" + Convert.ToInt32(stu_Age.Text) + "','" + Convert.ToInt32(stu_Semester.Text) + "','" + stu_City.Text + "')";
SqlCommand objSqlCommand = new SqlCommand(insertCommand, objSqlConnection);
objSqlCommand.ExecuteNonQuery();
//
this.studentsTableAdapter.Fill(this.personsDataSet.students);
//
MessageBox.Show("Student " + txtName.Text + " had been added Successfully", "Added Succefull", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
throw;
}
finally
{
objSqlConnection.Close();
}
}
答案 0 :(得分:1)
快捷的解决方法是在stu_ID
周围添加单引号,但是这很容易被SQL注入:“'” + stu_ID.Text +“'”
更好的方法是向查询中添加参数,以防止SQL注入:
string insertCommand = "INSERT INTO students VALUES (@stuID, @stuName, @stuAge, @stuSemester, @stuCity)";
insertCommand.Parameters.Add(new SqlParameter("stuId", stu_ID.Text));
command.Parameters.Add(new SqlParameter("stuName", stu_Name.Text));
command.Parameters.Add(new SqlParameter("stuAge", Convert.ToInt32(stu_Age.Text)));
command.Parameters.Add(new SqlParameter("stuSemester", Convert.ToInt32(stu_Semester.Text)));
command.Parameters.Add(new SqlParameter("stuCity", stu_City.Text));
答案 1 :(得分:0)
您的文本字段值需要用单引号引起来,例如:
"INSERT INTO students VALUES ('" + stu_ID.Text + "')"
但是,这仍然是一个非常糟糕的主意,因为您要对SQL Injection开放。如果您不打算在数据层上使用框架(例如Entity Framework),则至少需要使用SQLParameter来注入值。