我有一个应用程序可以向 sql server 添加新登录名,然后将其映射到所有数据库并使其成为“db_owner”(这些是要求......)。当我构建应用程序时,我使用了 SMO,一切都很完美。现在要求已经改变,我不能再使用 SMO 了没有添加登录名,也没有映射到所有数据库......但是当我在 SQL Server 管理工作室中执行这些行时,它工作得很好......
这些是命令-
create login dbUser WITH PASSWORD = 'passsword';
use DB_MyLog;
create user dbUser for login dbUser;
use DB_MyLog
EXEC sp_addrolemember 'db_owner','dbUser'
在我的应用程序中,我像这样运行它们 -
string connString = "Data Source=" + ConfigurationManager.AppSettings.Get("localhost_SQLEXPRESS")
+ ";Initial Catalog=" + "master" + ";User ID=" + ConfigurationManager.AppSettings.Get("user")
+ ";Password=" + ConfigurationManager.AppSettings.Get("password");
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString);
builder.AsynchronousProcessing = true;
using (SqlConnection sqlConnection1 = new SqlConnection(builder.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("CREATE LOGIN " + ConfigurationManager.AppSettings.Get("dbUser") +
" WITH PASSWORD=N'" + ConfigurationManager.AppSettings.Get("dbUserPass") + "' "
, sqlConnection1))
{
sqlConnection1.Open();
cmd.BeginExecuteNonQuery();
}
}
在另一种方法中我运行 -
string connString = "Data Source=" + ConfigurationManager.AppSettings.Get("localhost_SQLEXPRESS")
+ ";Initial Catalog=" + "master" + ";User ID=" + ConfigurationManager.AppSettings.Get("user")
+ ";Password=" + ConfigurationManager.AppSettings.Get("password");
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString);
builder.AsynchronousProcessing = true;
using (SqlConnection sqlConnection1 = new SqlConnection(builder.ConnectionString))
{
//get all databases
using (SqlCommand cmd = new SqlCommand("SELECT * FROM sys.sysdatabases", sqlConnection1))
{
sqlConnection1.Open();
SqlDataReader reader = cmd.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
using (SqlConnection sqlConnection2 = new SqlConnection(builder.ConnectionString))
{
sqlConnection2.Open();
using (SqlCommand cmd1 = new SqlCommand("use " + reader[0].ToString() + ";" +
"create user " + ConfigurationManager.AppSettings.Get("dbUser") + " for login " + ConfigurationManager.AppSettings.Get("dbUser") + ";" +
"use " + reader[0].ToString() +
" EXEC sp_addrolemember 'db_owner','" + ConfigurationManager.AppSettings.Get("dbUSer") + "'"
, sqlConnection2))
{
cmd1.BeginExecuteNonQuery();
}
}
}
// Call Close when done reading.
reader.Close();
}
}