简体   繁体   English

通过 C# 避免带参数的 SQL 注入?

[英]Avoiding SQL Injections with Parameters by C#?

I have recently adjusted my code to avoid getting SQL injections for maria db and got helped with adding parameters ,when I using parameters method page got running time error我最近调整了我的代码以避免为 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));

    }
}

I am relatively new to using maria db so any help is appreciated我对使用 maria db 比较陌生,因此感谢您提供任何帮助

If you want to avoid SQL injections, another approach besides parametrized queries is stored procedures.如果您想避免 SQL 注入,除了参数化查询之外,另一种方法是存储过程。

You can read it from here => https://www.techonthenet.com/mariadb/procedures.php or you can research on your own.您可以从这里阅读 => https://www.techonthenet.com/mariadb/procedures.php或者您可以自己研究。

Demo way of calling a stored procedure in an ASP.NET application:在 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();
        }
    }
}

(Code taken from https://www.aspsnippets.com/Articles/Call-MySql-Stored-Procedure-with-Parameters-in-ASPNet-C-and-VBNet.aspx ) (代码取自https://www.aspsnippets.com/Articles/Call-MySql-Stored-Procedure-with-Parameters-in-ASPNet-C-and-VBNet.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM