我正在尝试通过VBA找出SQL服务器的连接字符串中需要的内容.
这是我现在的代码,
Sub ConnectSqlServer() Dim conn As ADODB.Connection Dim rs As ADODB.Recordset Dim sConnString As String ' Create the connection string. sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _ "Initial Catalog=MyDatabaseName;" & _ "Integrated Security=SSPI;" ' Create the Connection and Recordset objects. Set conn = New ADODB.Connection Set rs = New ADODB.Recordset ' Open the connection and execute. conn.Open sConnString 'Do my stuff here If CBool(conn.State And adStateOpen) Then conn.Close Set conn = Nothing Set rs = Nothing End Sub
问题是我不知道在Connection字符串中放什么.我的完整文件路径就是这个.
C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\Staff_Manager.mdf
有人能说出需要的东西,
"Provider" "Source" "Initial Catalog"
谢谢.
请看这个链接.
http://www.connectionstrings.com/
另外,请参阅此示例脚本,该脚本对我来说非常合适.
Sub ADOExcelSQLServer() ' Carl SQL Server Connection ' ' FOR THIS CODE TO WORK ' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library ' Dim Cn As ADODB.Connection Dim Server_Name As String Dim Database_Name As String Dim User_ID As String Dim Password As String Dim SQLStr As String Dim rs As ADODB.Recordset Set rs = New ADODB.Recordset Server_Name = "EXCEL-PC\EXCELDEVELOPER" ' Enter your server name here Database_Name = "AdventureWorksLT2012" ' Enter your database name here User_ID = "" ' enter your user ID here Password = "" ' Enter your password here SQLStr = "SELECT * FROM [SalesLT].[Customer]" ' Enter your SQL here Set Cn = New ADODB.Connection Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _ ";Uid=" & User_ID & ";Pwd=" & Password & ";" rs.Open SQLStr, Cn, adOpenStatic ' Dump to spreadsheet With Worksheets("sheet1").Range("a1:z500") ' Enter your sheet name and range here .ClearContents .CopyFromRecordset rs End With ' Tidy up rs.Close Set rs = Nothing Cn.Close Set Cn = Nothing End Sub