开发者

How to build a parameterized query or user escaping in this SQL statement in C#?

command.CommandText = String.Format("CREAT开发者_JS百科E LOGIN {0} WITH password='{1}'", loginName, password);

loginName and password are based on some user input

I realize that it's bad practice to do it int this way but how to avoid sql injections here?


Call sp_addlogin instead - it's already parameterized


Here's how to parameterize your SQL. You may also want to check out this article on writing a DAO that handles this type of thing. I'm not sure if you can parameterize the LoginName. You're probably best off calling sp_addlogin like the previous poster said.

       command.CommandText=  @"CREATE LOGIN @LoginName WITH password=@Password";
        command.CommandType = CommandType.Text;
        command.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@LoginName",
                Value = "MyLoginNameValue",
                SqlDbType = SqlDbType.NVarChar,
                Size = 50
            });
        command.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@Password",
                Value = "MyPasswordValue",
                SqlDbType = SqlDbType.NVarChar,
                Size = 50
            });


It seems like the most right way to do it is to use SQL Server SMO SDK. I don't care of any other SQL engines since we'll never move from SQL Server for sure.


You can parameterize such queries by wrapping your DDL query in an exec as follows:

command.CommandText = "exec ('CREATE DATABASE ' + @DB)"

If you then add the parameter for @DB as usual this should work (in t-sql at least).

It should be possible to use CREATE LOGIN in the same fashion.


Can try something like this:

SqlCommand cmd = new SqlCommand(
                "CREATE LOGIN @login WITH password=@pwd", conn);
SqlParameter param  = new SqlParameter();
param.ParameterName = "@login ";
param.Value         = usertextforlogin; 
cmd.Parameters.Add(param);

param  = new SqlParameter();
param.ParameterName = "@pwd";
param.Value         = usertextforpwd;   

cmd.Parameters.Add(param);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜