ADO select statement with full text search with SQL injection

折月煮酒 提交于 2019-12-25 03:27:42

问题


The database that I am connecting to has a table with a Full Text Search index. This works correctly.

select * from MyTable where contains(*, 'value')

In WPF if I send that exact command down it works. However value is not hard coded it is something an user types in so it needs to be protected for SQL injection. The issue is that in doing so it does not return results. Here is my code;

DataTable dt = new DataTable();

        string ConString = "Data Source=127.0.0.1,1433;Initial Catalog=MyDB;User Id=sa;Password=amazingSecurePassword;";

        using (SqlConnection con = new SqlConnection(ConString))
        {
            string sqlCMD = "select * from MyTable where contains(*, @s1)"
            SqlCommand cmd = new SqlCommand(sqlCMD, con);
            SqlDataAdapter da = new SqlDataAdapter();

            try
            {
                con.Open();
                cmd = new SqlCommand(sqlCMD, con);
                cmd.Parameters.Add(new SqlParameter("@s1", "value"));

                da.SelectCommand = cmd;
                da.Fill(dt);
                con.Close();

            }
            catch (Exception x)
            {
                //Error logic
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }
        }

Edit: @Mike comment worked. Change the SqlDbType.NVarChar fixed the issue


回答1:


As noted in the above comment, setting the SQlDbType to NVarChar during the creation of the SqlParameter helps the CLR determine the right data type. More info about the SqlParameter constructor at MSDN.



来源:https://stackoverflow.com/questions/24959155/ado-select-statement-with-full-text-search-with-sql-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!