C# 调试c中参数化查询的最佳方法
基于上面帖子中的问题,大多数人认为参数化查询是避免sql注入的最佳解决方案 下面是我使用sql注入的代码C# 调试c中参数化查询的最佳方法,c#,parameterized-query,C#,Parameterized Query,基于上面帖子中的问题,大多数人认为参数化查询是避免sql注入的最佳解决方案 下面是我使用sql注入的代码 public DataSet checkemp(string user) { strsql = "SELECT * from employee where employeeid = @userid"; SqlConnection con = new SqlConnection(connectionString); SqlDataAdapter da = new Sql
public DataSet checkemp(string user)
{
strsql = "SELECT * from employee where employeeid = @userid";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(strsql, connectionString);
da.SelectCommand.Parameters.Add("@userid", SqlDbType.VarChar, 50).Value = user;
// pretend the user name is "Micheal"
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();
return ds;
}
在调试过程中,如果我指向strsql标签,我只能从employee中获取查询SELECT*,其中employeeid=@userid,而不能从employee中获取查询SELECT*,其中employeeid='Micheal'
有没有什么解决方案可以解决这个问题并使之最有效?谢谢大家 试试MiniProfiler:
ADO.NET探查器,能够分析原始ADO.NET上的调用
**您可能需要将SqlCommand与ProfiledDbCommand包装在一起我将引入一个扩展方法,尽管这不是必须的,但实际逻辑更重要,它返回解析的查询,如下所示,并且仅在调试模式下调用:
请注意,尽管为了简洁起见,我直接编写了扩展方法,但它实际上应该在一个单独的静态类中定义。简单的答案是否定的,在employeeid为'Micheal'的employee中,无法将命令视为SELECT*from employee。如果你想测试查询,为什么不在sql server中执行呢?这意味着在调试过程中,我需要在查询中手动插入参数值来重新计算@userid并在sql server上运行?Yogi,如何使用user profiler查看实际的sql语句?
public DataSet checkemp(string user)
{
strsql = "SELECT * from employee where employeeid = @userid";
SqlConnection con = GetOpenConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(strsql, connectionString);
da.SelectCommand.Parameters.Add("@userid", SqlDbType.VarChar, 50).Value = user;
// pretend the user name is "Micheal"
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();
return ds;
}
public static DbConnection GetOpenConnection(string connectionString)
{
var cnn = new SqlConnection(connectionString);
// wrap the connection with a profiling connection that tracks timings
return new StackExchange.Profiling.Data.ProfiledDbConnection(cnn, MiniProfiler.Current);
}
public void TestMethod()
{
string cmdStr = "<some sql command text>";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(cmdStr, con);
cmd.Parameters.AddWithValue("<param1>", <value1>); // add parameter in any way you want
#if DEBUG
string parsedQuery = cmd.GetParsedQuery();
Console.WriteLine(parsedQuery); // or whatever
#endif
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();
return ds;
}
public static string GetParsedQuery(this SqlCommand cmd)
{
if(cmd.CommandType == CommandType.Text)
{
string parsedQuery = cmd.CommandText;
foreach(var p in cmd.Parameters)
{
parsedQuery = parsedQuery.Replace(p.ParameterName, Convert.ToString(p.Value));
}
return parsedQuery;
}
return null;
}