执行查询以将数据从VBA插入到MySQL以及所说的数据将是什么样的

时间:2015-08-05 10:42:37

标签: mysql vba

我正在尝试将word文档的片段插入MySQL数据库。我在Java中这样做了,但是我丢失了所有格式的Microsoft文档,所以我现在尝试在VBA中做同样的事情(我希望这会保留格式化?!)。 但是为了找出它是否会,我需要尝试..我已经在MySQL中建立了连接和表,但是我无法插入任何值。它会在“conn.Execute”行上引发语法错误。

Sub ConnectToDataBase()

'
'
 Dim conn As New ADODB.Connection
 Dim Server_Name As String
 Dim Database_Name As String
 Dim User_ID As String
 Dim Password As String
 '
 Dim i As Long ' counter
 Dim SQLStr As String ' SQL to perform various actions
 Dim table1 As String, table2 As String
 Dim field1 As String, field2 As String
 Dim rs As ADODB.Recordset
 Dim vtype As Variant
 '


 Server_Name = "127.0.0.1" ' Enter your server name here -
 Database_Name = "rmp" ' Enter your database name here
 User_ID = "root" ' enter your user ID here
 Password = "Password1" ' Enter your password here

 Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 3.51 Driver}" _
 & ";SERVER=" & Server_Name _
 & ";DATABASE=" & Database_Name _
 & ";UID=" & User_ID _
 & ";PWD=" & Password _
 & ";OPTION=16427" ' Option 16427 = Convert LongLong to Int: 

 strSQL = "INSERT INTO  parts(idParts, Part 1, Part 2, Part 3, Part 4, 
 Part 5) " & _
            "VALUES (' " & 2 & " ' , '" & one & "' , '" & two & "' , '" &  
  three & "' , '" & four & "' , '" & five & "' )"

conn.Execute strSQL


Close connections
On Error Resume Next
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
On Error GoTo 0

End Sub

1 个答案:

答案 0 :(得分:0)

.Net连接器使用UID,但VBA使用的ODBC连接器使用User。我也只使用过Option=3

conn.Open "DRIVER={MySQL ODBC 3.51 Driver}" _
    & ";SERVER=" & Server_Name _
    & ";DATABASE=" & Database_Name _
    & ";User=" & User_ID _
    & ";PWD=" & Password _
    & ";OPTION=16427" ' Option 16427 = Convert LongLong to Int:

您可以通过运行简单的SQL查询来测试连接。

strSQL = "SELECT * FROM parts;"
conn.Execute strSQL

如果这会引发错误,您仍有问题。

此外,在您的代码中,2的任意一侧都有空格。这是对的吗?

  

“VALUES('”& 2&“',