2017-02-10 77 views
0

我都已經通過一些教程走了,我的連接不停地進行故障的SQL數據庫,我已經嘗試了很多不同的連接方式。連接到從Excel

我通過mySQL工作臺連接到mySQL。我正在使用IP地址和端口號,然後使用我的憑據登錄。這工作得很好,我能夠做我需要的查詢。

我現在正在試圖通過Excel來訪問這個數據庫,最好是通過VBA。我試圖創建一個新的連接,但我似乎沒有任何工作。我不知道要將什麼放入我的strConn字符串中。

我目前正在使用:

Options Explicit 
Private Sub CommandButton2_Click() 
    Dim cn As ADODB.Connection 
    Dim rs As ADODB.Recordset 
    Dim strConn As String 

    Set cn = New ADODB.Connection 
    strConn = "DRIVER={MySQL ODBC 5.3.7 Driver};" & _ 
       "SERVER=XXX.XXX.X.X;" & _ 
       "PORT=3306" & _ 
       "DATABASE=cahier_de_lab;" & _ 
       "UID=xxx;" & _ 
       "PWD=xxx;" & _ 
       "Option=3" 

    cn.Open strConn 

    ' Find out if the attempt to connect worked. 
    If cn.State = adStateOpen Then 
      MsgBox "Welcome to Pubs!" 
    Else 
      MsgBox "Sorry. No Pubs today." 
    End If 

    ' Close the connection. 
    cn.Close 

End Sub 

感謝您的幫助!

+1

司機看起來我錯了。 –

+0

這是... https://www.google.com.au/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=vba+mysql+driver+connection+string –

+0

您可能需要建立一個odbc連接。 –

回答

0

從Excel導出到SQL Server。

Sub InsertInto() 

'Declare some variables 
Dim cnn As adodb.Connection 
Dim cmd As adodb.Command 
Dim strSQL As String 

'Create a new Connection object 
Set cnn = New adodb.Connection 

'Set the connection string 
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PC\SQLEXPRESS" 
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PC\SQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes" 


'Create a new Command object 
Set cmd = New adodb.Command 

'Open the Connection to the database 
cnn.Open 

'Associate the command with the connection 
cmd.ActiveConnection = cnn 

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure 
cmd.CommandType = adCmdText 

'Create the SQL 
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2" 

'Pass the SQL to the Command object 
cmd.CommandText = strSQL 


'Execute the bit of SQL to update the database 
cmd.Execute 

'Close the connection again 
cnn.Close 

'Remove the objects 
Set cmd = Nothing 
Set cnn = Nothing 

End Sub 

OR。 。 。 。

Import from SQL Server into Excel . . . . . 


Sub Create_Connectionstring() 

Dim objDL As MSDASC.DataLinks 
Dim cnt As ADODB.Connection 
Dim stConnect As String 'Instantiate the objects. 

Set objDL = New MSDASC.DataLinks 
Set cnt = New ADODB.Connection 

On Error GoTo Error_Handling 'Show the Data-link wizard 
stConnect = objDL.PromptNew 'Test the connection. 
cnt.Open stConnect 'Print the string to the VBE Immediate Window. 
Debug.Print stConnect 'Release the objects from memory. 
exitHere: 
    cnt.Close 
    Set cnt = Nothing 
    Set objDL = Nothing 
Exit Sub 

Error_Handling: 'If the user cancel the operation. 
If Err.Number = 91 Then 
    Resume exitHere 
End If 
End Sub 
+0

原始海報指定MySQL。 –

+0

是的,它確實是我試圖連接到的MySQL數據庫。 – JahKnows