Create Sql Server Authentication Account?

前端 未结 1 1850
清歌不尽
清歌不尽 2021-01-15 08:36

I want to create an Sql Server Authentication Account, not a user in the database or in the account.

What i mean is that i want to create an account so i can login f

相关标签:
1条回答
  • 2021-01-15 09:31

    There are only two modes that I know you can use: Windows or SQL Server Authentication. This means you are limited to only two choices: You either use a Windows account, or you create an SQL Server login that you can use to authenticate.

    EDIT:

    To programmatically create an sql server login, you could use Sql Server Management objects. I notice you didn't say whether you want to do this from a Windows (desktop) or Web application. To use Sql Server Management to create a login (or do any sort of "management"), the code would need to run with higher privileges - say local or domain account with sufficient privileges to administer the SQL server instance.

    You will need to add references to (you could use version 9.0 of the assemblies):

    Microsoft.SqlServer.ConnectionInfo
    Microsoft.SqlServer.Smo
    Microsoft.SqlServer.SqlEnum
    

    With that, the following code is enough to create an SQL login and also add the user to your target database

            var serverName = "."; // Your SQL Server Instance name
            var databaseName = "Test"; // Your database name
            var loginName = "testuserY"; // Your login name (should not exist - or you should add code to check if the login exists)
    
    
            Server svr = new Server(serverName);
            var db = svr.Databases[databaseName];
            if (db != null)
            {
                // You probably want to create a login and add as a user to your database
                Login login = new Login(svr, loginName);
                login.DefaultDatabase = "master"; // Logins typically have master as default database
                login.LoginType = LoginType.SqlLogin;
                login.Create("foobar", LoginCreateOptions.None); // Enter a suitable password
                login.Enable();
    
                User user = new User(db, loginName);
                user.UserType = UserType.SqlLogin;
                user.Login = login.Name;
                user.Create();
                // add a role
                user.AddToRole("db_owner");
            }
    

    You will need to add:

    using Microsoft.SqlServer.Management.Smo;
    

    You can add try{} catch{} blocks and plumbing code to make it more robust you would recover gracefully in case of failure

    0 讨论(0)
提交回复
热议问题