我每次在這裏提出關於數據庫的問題時都會聽到有關參數化查詢的消息。它看起來像我沒有使用參數化查詢,我的代碼可能會遭受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'單引號作爲一個正常的字符串。 –
@JoachimIsaksson哦謝謝 – yrazlik