C#
public DataTable GetDataTable(string spname,string parameters)
{
DatatTable dt=new DataTable();
try
{
using(sqlcommand cmd=new sqlcommand("",conn))
{
ArrayList aParams;
string[] avalues=parameters.Split(new String[] {"_"},StringSplitOptions.None);
cmd.CommandType=CommandType.StpredProcedure;
cmd.CommandText=spname;
cmd.CommandTimeOut=Convert.ToInt32(ConfigurationManager.AppSettings[CommandTimeOut]);
aParams=GetParameterList(spname);
for(Int32 i=0;i<aParams.Count;i++)
{
cmd.Parameters.Add(new SqlParameters((String)aParams[i],(String)aValues[i]));
}
conn.Open();
SqlDataReader strReader;
strReader=cmd.ExecureReader();
While(strReader.Read())
{
dt.Rows.Add(strReader[0].ToString());
}
conn.Close();
}
}
Catch(Exception ex)
{
//return ex;
}
return dt;
}Note: I am getting SQL Injection issue on this line " strReader=cmd.ExecureReader();".Please give me some suggestion to resolve this SQL Injection issues.


Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Jan 17, 2023, 9:06 AM EST
Hi Dibyajyoti,
This code has a major security vulnerability, it does not properly validate or sanitize the user input passed to the stored procedure which could lead to SQL injection attacks.
The problem is with the following line:
cmd.Parameters.Add(new SqlParameters((String)aParams[i],(String)aValues[i]));
I suggest using parameterized queries to protect against SQL injection attacks, also check if the input is valid before using it in SQL statement, and you should also consider logging any errors or exceptions that may occur during the execution of the function.
Sachin SinghRank #66 · 26.2K reputationPosted Jan 16, 2023, 2:24 AM EST
There is no issue in the shared code.
I guess your stored procedure might have some issue, make sure you are not concatinating values using '+' sign in your stored procedure.
Naimish MakwanaRank #324 · 7.7K reputationPosted Jan 16, 2023, 3:09 AM EST
Please refer below link.
https://dba.stackexchange.com/questions/127/do-stored-procedures-prevent-sql-injection
Dibyajyoti PalataRank #7,171 · 247 reputationPosted Jan 17, 2023, 8:15 AM EST
I checked stored procedure working fine and also getting expacted output.
Dibyajyoti PalataRank #7,171 · 247 reputationPosted Jan 23, 2023, 12:47 PM EST
for(Int32 i=0;i
cmd.Parameters.Add(new SqlParameters((String)aParams[i],(String)aValues[i]));
}
In above method multiple SP calling based on SP multipule times adding parameter and values.So SQL Injection will prevent.
How to avoid sql injection ? Any predefine functions to handle dynamic parameter and value.
How to write sanitize method to handle that parameters ?
Please guid me.