通过 C# 避免 SQL 参数注入?
Avoiding SQL Injections with Parameters by C#?
我最近调整了我的代码以避免对 maria db 进行 SQL 注入,并在添加参数方面得到了帮助,当我使用参数方法页面时出现 运行 时间错误
strSQL = "SELECT * from user where uid = @uid AND start >= @StartDate AND end <= @EndDate ";
DataSet ds = QueryDataSet(strSQL, uid , StartDate, EndDate);
public DataSet QueryDataSet(string strSQL,string uid , string StartDate, string EndDate)
{
try
{
MySqlDataAdapter da = new MySqlDataAdapter(strSQL, DBconn);
da.SelectCommand.Parameters.AddWithValue("@uid", uid );
da.SelectCommand.Parameters.AddWithValue("@StartDate", StartDate);
da.SelectCommand.Parameters.AddWithValue("@EndDate", EndDate);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
catch (Exception ex)
//catch
{
throw (new System.Exception(ex.Message));
}
}
我对使用 maria db 比较陌生,所以非常感谢您的帮助
如果您想避免 SQL 注入,除了参数化查询之外的另一种方法是存储过程。
您可以从这里阅读 => https://www.techonthenet.com/mariadb/procedures.php
或者你可以自己研究。
在 ASP.NET 应用程序中调用存储过程的演示方式:
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("Customers_GetCustomer", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CustId", customerId);
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
我最近调整了我的代码以避免对 maria db 进行 SQL 注入,并在添加参数方面得到了帮助,当我使用参数方法页面时出现 运行 时间错误
strSQL = "SELECT * from user where uid = @uid AND start >= @StartDate AND end <= @EndDate ";
DataSet ds = QueryDataSet(strSQL, uid , StartDate, EndDate);
public DataSet QueryDataSet(string strSQL,string uid , string StartDate, string EndDate)
{
try
{
MySqlDataAdapter da = new MySqlDataAdapter(strSQL, DBconn);
da.SelectCommand.Parameters.AddWithValue("@uid", uid );
da.SelectCommand.Parameters.AddWithValue("@StartDate", StartDate);
da.SelectCommand.Parameters.AddWithValue("@EndDate", EndDate);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
catch (Exception ex)
//catch
{
throw (new System.Exception(ex.Message));
}
}
我对使用 maria db 比较陌生,所以非常感谢您的帮助
如果您想避免 SQL 注入,除了参数化查询之外的另一种方法是存储过程。
您可以从这里阅读 => https://www.techonthenet.com/mariadb/procedures.php 或者你可以自己研究。
在 ASP.NET 应用程序中调用存储过程的演示方式:
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand("Customers_GetCustomer", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CustId", customerId);
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}