在mvc .net中将参数传递给数据库的安全方法

时间:2018-03-22 18:31:55

标签: .net asp.net-mvc

我是.Net的新手,我被告知以下方式增加了SQL注入的可能性,你能举例说明我应该做什么而不是像这样写我的代码吗?

NpgsqlCommand cmd = null;
NpgsqlConnection con = null;

DataTable dt_datat_for_chart = new DataTable();

string cnction = null;
string cn = System.Configuration.ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
con = new NpgsqlConnection(cn);

NpgsqlDataAdapter dataForGrid_Adapter = new NpgsqlDataAdapter(@"select turbine_name,round(current_days_avg_winds_speed,2)
                                                                 Wind,round(current_days_availability,2) Avalability,current_days_production,last_state_change_timestamp::timestamp(0)
                                                                 from wpv.v_master_data_turbine v1
                                                                 JOIN zd.t_users g on(g.user_id=v1.pv_person_resp_id)

                                                                 AND current_turbine_status='" + statType + @"' order by last_state_change_timestamp desc", cn);
dataForGrid_Adapter.Fill(dt_datat_for_chart);

1 个答案:

答案 0 :(得分:1)

我认为这有帮助

 // 1. declare command object with parameter 
 NpgsqlCommand  cmd = new NpgsqlCommand ("select * from Customers where city = @City", conn);

 // 2. define parameters used in command object 
NpgsqlParameter  param = new NpgsqlParameter (); 
param.ParameterName = "@City"; 
param.Value         = inputCity;

 // 3. add new parameter to command object 
 cmd.Parameters.Add(param);