You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL Server创建数据库登录及C#代码配置的问题咨询

问题描述

我正在开发基于.NET 4.5、Entity Framework和SQL Server 2019的C# Windows Forms项目,已经实现可自动完成所有操作的静默安装包,运行正常。

现在想在首次运行并创建数据库后做安全配置:在SQL Server中创建新登录名并分配给我的数据库。尝试编写了代码,但因为不知道Sa默认密码(网上找的默认密码RPSsql12345不对)报错,同时不确定当前实现方式是否正确。

我的代码

namespace DataAccessLayer
{
    public class DACheckDatabase
    {
        public void CreateDatabase()
        {
            // Check if database exists
            if (!DatabaseExists())
            {
                // Create new database
                using (var context = new DB())
                {
                    string connectionString = "Data Source=DESKTOP-JU6B73e\\SQL2019;Initial Catalog=master;User ID=sa;Password=RPSsql12345;";

                    SqlConnection connection = new SqlConnection(connectionString);
                    connection.Open();

                    string username = "test";
                    string password = "1234";
                    string createLoginQuery = $"CREATE LOGIN {username} WITH PASSWORD = '{password}'";

                    SqlCommand createLoginCommand = new SqlCommand(createLoginQuery, connection);
                    createLoginCommand.ExecuteNonQuery();

                    context.Database.Create();
                    
                    string databaseName = "testDB";
                    string assignLoginQuery = $"USE {databaseName}; CREATE USER {username} FOR LOGIN {username}; EXEC sp_addrolemember 'db_owner', '{username}'";

                    SqlCommand assignLoginCommand = new SqlCommand(assignLoginQuery, connection);
                    assignLoginCommand.ExecuteNonQuery();
                }
            }
        }

        private bool DatabaseExists()
        {
            using (var context = new DB())
            {
                return context.Database.Exists();
            }
        }
    }
}

app.config中的连接字符串

"data source=DESKTOP-JU6B73e\SQL2019;initial catalog=testDB;User Id=test;password=1234;Trusted_Connection=False;"

内容的提问来源于stack exchange,提问作者sadegh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:43:15