command.CommandText = String.Format("CREATE 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?
调用sp_addlogin
- 它已经参数化了
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.