简体   繁体   English

如何在C#中的SQL语句中构建参数化查询或用户转义?

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

command.CommandText = String.Format("CREATE LOGIN {0} WITH password='{1}'", loginName, password);

loginName and password are based on some user input loginName和password基于某些用户输入

I realize that it's bad practice to do it int this way but how to avoid sql injections here? 我意识到这样做是不好的做法但是如何避免在这里进行sql注入?

调用sp_addlogin - 它已经参数化了

Here's how to parameterize your SQL. 以下是如何参数化SQL。 You may also want to check out this article on writing a DAO that handles this type of thing. 您可能还想查看有关编写处理此类事物的DAO的这篇文章 I'm not sure if you can parameterize the LoginName. 我不确定你是否可以参数化LoginName。 You're probably best off calling sp_addlogin like the previous poster said. 你可能最喜欢调用sp_addlogin,就像上一张海报所说的那样。

       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. 看起来最合适的方法是使用SQL Server SMO SDK。 I don't care of any other SQL engines since we'll never move from SQL Server for sure. 我不关心任何其他SQL引擎,因为我们永远不会从SQL Server迁移。

You can parameterize such queries by wrapping your DDL query in an exec as follows: 您可以通过将DDL查询包装在exec来参数化此类查询,如下所示:

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

If you then add the parameter for @DB as usual this should work (in t-sql at least). 如果你像往常一样为@DB添加参数,这应该可行(至少在t-sql中)。

It should be possible to use CREATE LOGIN in the same fashion. 应该可以以相同的方式使用CREATE LOGIN

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);

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

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