且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Mysql查询以避免SQL注入

更新时间:2023-02-05 21:10:19

我将向您展示一个例子。剩下的你应该能够做到:

您的查询:

  string  sel =   SELECT u.Id as ID,u.Name,u.IName,s.FId,s。 TId,s.data,s.Date,s.ID as Id,s.iurl,s.Id as SpId,s.ITitle FROM mydb.userdb as u,mydb.psp as s WHERE u.Id = s.FId AND s.FId =' + Session [  UId]。ToString()+  's by sdI DESC; 





您的查询文字将是:

  string  sel =   SELECT u.Id as ID,u.Name,u.IName,s.FId,s.TId,s.data ,s.Date,s.ID as Id,s.iurl,s.Id as SpId,s.ITitle from mydb.userdb as u,mydb.psp as s WHERE u.Id = s.FId AND  s。 FId = @ FID 按顺序排序.Id DESC 





您的查询已定义并且可以与你的MySqlCommand和MySqlConnection一起使用。

所以:

  void  GetMyUserDetail( int  ID)
{
使用(MySqlConnection conn = new MySqlConnection(connStr))
{
const string sel = SELECT u.Id as ID,u.Name,u.IName,s .FId,s.TId,s.data,s.Date,s.ID as Id,s.iurl,s.Id as SpId,s.ITitle FROM mydb.userdb as u,mydb.psp as s WHERE u.Id = s.FId AND s.FId=@FID order by s.Id DESC;

使用(MySqlCommand cmd = new MySqlCommand(sel,conn))
{
cmd.Parameters.AddWithValue( @ FID,ID); // 是方法的参数
conn.Open();
使用(MySqlDataReader rdr = cmd.ExecuteReader())
{
(rdr.Read())
{
// 对结果集执行某些操作
}
}
}
}
}





更多信息: MySQL :: MySQL Connector / Net开发人员指南:: 4.1.4使用参数 [ ^ ](这是Google为您提供的55,000个结果中的1个)


除了上面的digimanus解决方案之外,还要考虑使用存储过程 - MySQL :: MySQL Connector / Net开发人员指南:: 4.1.5使用存储过程 [ ^ ]。您仍然可以传递参数。



请参阅此文章以获取示例为MySql存储过程IN,OUT和INOUT参数工作C#代码 [ ^ ]



也可以通过阅读本文来考虑动态sql的危险如何防止存储过程中的SQL注入 [ ^ ]


每次动态构建带有您无法控制的参数的SQL查询时,您都是注入SQL的风险。

类似

 C md =   SQL推荐使用filter =' +参数+   '; 



应该给

SQL推荐 filter = ' parameter_value'



但是恶意参数会导致完全不同的东西。

例如,如果你有

参数=   a'; \ nMalicious SQL表示赞赏; \\带有filter ='a'; 



你带来的最终结果

 SQL推荐  filter = '  a' ; 
恶意SQL表扬;
dummy SQL with filter = ' a'



并且客户端注入了SQL推荐。



这只是一个原理演示,细节会有所不同。



SQL注入 - ***,免费的百科全书 [ ^ ]

SQL注入 [ ^ ]



对于downvoter,请随时告诉我这里有什么问题。


following are some MySQL queries :

1]

string sel=SELECT u.Id as ID,u.Name,u.IName,s.FId,s.TId,s.data,s.Date,s.ID as Id,s.iurl,s.Id as SpId,s.ITitle  FROM mydb.userdb as u,  mydb.psp as s WHERE u.Id=s.FId AND s.FId='" + Session["UId"].ToString() + "'order by s.Id DESC";



2]

string postlob = "Insert into mydb.`dbo.sp`(ITitle,FId,TId,D,imageurl,SendDate,d,dn)SELECT ITitle,FromId,ToId,data,iurl,Date,0,0 from mydb.personalscrap where Id='" + test + "'";



3]

string deletpass = "delete from  mydb.pesp where  Id='" + test + "'";



4]

string postlob = " INSERT INTO mydb.sp2(ITitle, pbyid,`Name`, sid, data, fstatus, iurl, date, pid,d,dn)SELECT(select ITitle from mydb.psp where Id = '"+test+"' ) ,(select FId from mydb.psp where Id = '"+test+"'),(select `Name` from mydb.user where Id = '1'),FId,(select data from mydb.psp where Id = '"+test+"'),FStatus,(select iurl from mydb.psp where Id = '"+test+"'),(select date from mydb.psp where Id = '" + test + "'),(select max(Id) + 1 from mydb.sp2),0,0 from mydb.`dbo.tbl` where Id = '" + Session["UId"] + "'  AND FStatus = '1'";




5]

string queryupdate = "Update  mydb.psp set data='" + sugg + "' where Id='" + test + "'";


please help me to make above queries sql injection free.

I go through some article and used them for insert queries but now when insert query nested with select query then how to perfoem parameterized query to avoid sql injection.


I also want to get know how to pass parameters here

MySqlCommand cmd = connection.CreateCommand();
              cmd.CommandText = SelectQuery;
              MySqlDataAdapter ada = new MySqlDataAdapter(cmd);

              DataTable dtt = new DataTable();
              ada.Fill(dtt)
              return dtt;

I'll show you 1 example. The rest you should be able to do yourself:
Your query:
string sel="SELECT u.Id as ID,u.Name,u.IName,s.FId,s.TId,s.data,s.Date,s.ID as Id,s.iurl,s.Id as SpId,s.ITitle  FROM mydb.userdb as u,  mydb.psp as s WHERE u.Id=s.FId AND s.FId='" + Session["UId"].ToString() + "'order by s.Id DESC";



Your querytext will be:

string sel = "SELECT u.Id as ID,u.Name,u.IName,s.FId,s.TId,s.data,s.Date,s.ID as Id,s.iurl,s.Id as SpId,s.ITitle  FROM mydb.userdb as u, mydb.psp as s WHERE u.Id=s.FId AND s.FId=@FID order by s.Id DESC"



Your query is defined and can be used with your MySqlCommand and MySqlConnection.
So:

void GetMyUserDetail(int ID)
{
    using (MySqlConnection conn = new MySqlConnection(connStr))
    {
        const string sel = "SELECT u.Id as ID,u.Name,u.IName,s.FId,s.TId,s.data,s.Date,s.ID as Id,s.iurl,s.Id as SpId,s.ITitle  FROM mydb.userdb as u, mydb.psp as s WHERE u.Id=s.FId AND s.FId=@FID order by s.Id DESC";
                
        using (MySqlCommand cmd = new MySqlCommand(sel, conn))
        {
            cmd.Parameters.AddWithValue("@FID", ID); // is parameter from method
            conn.Open();
            using (MySqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    // do something with your resultset
                }
            }
        }
    }
}



More information: MySQL :: MySQL Connector/Net Developer Guide :: 4.1.4 Working with Parameters[^] (which is 1 of 55,000 results Google gives you on this subject)


In addition to the solution from digimanus above also consider using Stored Procedures - MySQL :: MySQL Connector/Net Developer Guide :: 4.1.5 Working with Stored Procedures[^]. You would still pass parameters.

See this article for an example Working C# code for MySql Stored Procedures IN, OUT, and INOUT parameters[^]

And also consider the dangers of dynamic sql by reading this article too How to prevent SQL Injection in Stored Procedures[^]


Every time you dynamically build an SQL query with parameters you don't control, you are at risk of SQL injection.
Anything like
Cmd= "SQL commend with filter='"+parameter+"'";


is supposed to give

SQL commend with filter='parameter_value'


but a malicious parameter can lead to something completely different.
for exemple, if you have

parameter="a';\nMalicious SQL commends;\ndummy SQL with filter='a'";


you end up with

SQL commend with filter='a';
Malicious SQL commends;
dummy SQL with filter='a'


And SQL commend have been injected from client side.

this is only a demo of principle, details will be different.

SQL injection - Wikipedia, the free encyclopedia[^]
SQL Injection[^]

To downvoter, feel free to tell me what is wrong here.