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

为何该代码无需用户名和密码即可访问SQL Server?

为什么这段代码无需输入用户名密码就能访问SQL Server?

先看对应的运行效果:
输入图片描述

上述输出由以下代码生成:

using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        DataTable dataTable = SmoApplication.EnumAvailableSqlServers(true);
        listBox1.ValueMember = "Name";
        listBox1.DataSource = dataTable;
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        listBox2.Items.Clear();
        if (listBox1.SelectedIndex != -1)
        {
            string serverName = listBox1.SelectedValue.ToString();
            Server server = new Server(serverName);
            try
            {
                foreach (Database database in server.Databases)
                {
                    listBox2.Items.Add(database.Name);
                }
            }
            catch (Exception ex)
            {
                string exception = ex.Message;
            }
        }
    }
}

这其实是因为这段代码用了Windows集成身份验证,这是SQL Server默认支持的一种安全验证方式,具体原因如下:

  • 当你通过new Server(serverName)创建Server实例时,Smo库默认会采用Windows身份验证模式,它会自动借用当前运行这个WinForm程序的Windows用户身份,去和SQL Server做验证,不需要手动输入账号密码。
  • 前提是你的Windows账号已经被SQL Server授权了——比如这个账号是SQL Server的管理员组成员,或者被分配了访问对应数据库的权限,这样才能顺利连接并读取数据库列表。
  • 这种方式比手动输入账号密码的SQL Server身份验证更安全,也更适合域环境下的团队协作,不用在代码里硬编码敏感的账号密码信息,减少了泄露风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:17:49