我有一個應用程序可以添加新的登錄到sql服務器,然後將其映射到所有的數據庫,並使其'db_owner'(這些是要求...)。 當我構建應用程序時,我使用了SMO並且一切都很完美。 現在的需求已經改變,我不能再使用SMO:( 所以我需要從我的應用程序運行T-SQL命令而不是... 我的問題是當我運行應用程序什麼都沒有發生在SQL服務器 - 登錄不會被添加,它不會被映射到所有數據庫....但是當我在SQL服務器管理工作室中執行這些行時,它工作得很好...從.net運行T-SQL命令
這些是命令 -
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();
}
}
如果使用'BeginExecuteNonQuery'併發生錯誤,則它只會在回調處理程序中變爲可見。也許調用'ExecuteNonQuery'而不是'BeginExecuteNonQuery'。 – Andomar 2012-07-08 08:34:38
@Andomar當我將BeginExecuteNonQuery更改爲ExecuteNonQuery時,我能夠捕捉到我的異常並修復了我的錯誤....現在它可以正常工作,謝謝...如果將此建議添加到答案中,我會接受它... – 2012-07-08 09:17:18