VBA 连接到 SQL Server Express 数据库问题

VBA connecting to SQL Server Express database issue

我安装了一份 SQL Server Express(最新)。我无法连接到它。

既然我是这台电脑的admin,应该不需要用户名密码,因为数据库是我创建的,一切都应该在Windows认证下。我的代码如下。

我收到一个错误:

Run-time error '-2147217843 (80040e4d)':
Invalid authorization specification

尝试打开连接时发生此错误。

当我从主窗体启动子窗体时,此代码在初始化中运行:

Option Explicit
Private objMyConn As ADODB.Connection
Private objMyRecordset As ADODB.Recordset

Private Sub UserForm_Initialize()
    'Declare variables'
        Set objMyConn = New ADODB.Connection
        Set objMyRecordset = New ADODB.Recordset
        Dim strSQL As String

        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Contact;"
        objMyConn.Open

        strSQL = "Select * from Contact where Lastname like " + Chr(39) + "%" + LastSearch + Chr(39) + " And Firstname like " + Chr(39) + "%" + FirstSearch + Chr(39)
        MsgBox strSQL

End Sub

Integrated Security=SSPI 添加到您的连接字符串以指示需要可信连接:

objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Contact;Integrated Security=SSPI"

编辑

SQL Server Express 默认安装命名实例,因此您可能需要更改数据源以包含实例名称:

objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;Initial Catalog=Contact;Integrated Security=SSPI"

用这样的东西代替 localhost

HP8300-0792\SQLEXPRESS

其中 HP8300-0792 是您计算机的名称。