每次我在这里询问有关数据库的问题时,我都听说过参数化查询。看起来我没有使用参数化查询,我的代码可能会受到 SQL 注入的影响。所以这是我的代码:
public void CreateStudent(int ID, String status, String email, String firstName, String lastName, String password, String level, String program)
{
SqlConnection con = new SqlConnection(GetConnectionString());
string query1 = "insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values ("
+ "'" + firstName + "'" + "," + "'" + lastName + "'" + ","
+ "'" + ID + "'" + "," + "'" + email + "'" + "," + "'" + level + "'" + "," + "'" + program + "'" + "," + "'" + status + "'"
+ "," + "'" + password + "'" + "," + "'" + "Student" + "'" + ")";
SqlCommand command = new SqlCommand(query1,con);
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
}
这是我尝试过的:
SqlConnection con = new SqlConnection(GetConnectionString());
string query1 = "insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values(@firstName,@lastName,@ID,@email,@level,@program,@status,@password,Student)";
SqlCommand command = new SqlCommand(query1,con);
command.Parameters.AddWithValue("@firstName", firstName);
command.Parameters.AddWithValue("@lastName", lastName);
command.Parameters.AddWithValue("@ID", ID);
command.Parameters.AddWithValue("@email", email);
command.Parameters.AddWithValue("@level", level);
command.Parameters.AddWithValue("@program", program);
command.Parameters.AddWithValue("@status", status);
command.Parameters.AddWithValue("@password", password);
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
这给出了一个错误,指出 Student 是一个无效的列名。实际上,这里我尝试使用“Student”作为要添加到列 Type 的字符串值。有人可以将此查询编写为参数化查询以便我理解吗?