为什么能够使用excel VBA(通过我在下面显示的公共函数中看到的ODBC连接器)连接到MySQL数据库来INSERT记录以及SELECT语句,但是当我尝试时会收到错误声明删除记录?当我使用Root帐户连接时,我仍然遇到同样的问题。我是MySQL新手,我正在使用安装程序时出现的Sakila数据库。
我可能会错过什么?
请参阅下面的我用于连接数据库的函数,以及适用于INSERT和SELECT语句的代码示例,以及使用DELETE语句出错的代码。
... REVISION
事实证明,这在我的MySQL声明中是一个令人尴尬的错误,如接受的答案中所指出的那样。但是,对于那些想要通过Excel-VBA连接到MySQL的人来说,你可能会发现connectDatabase()和closeDatabase()函数的优点,因为大多数代码我偶然发现ODBC连接器有用户以不太干净的格式创建连接。
Public DBCONT As Object
Public Function connectDatabase()
Set DBCONT = CreateObject("ADODB.Connection")
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim sConn As String
Server_Name = "localhost"
Database_Name = "sakila"
User_ID = "admin"
Password = "password"
sConn = "Driver={MySQL ODBC 5.1 Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";UID=" & User_ID & ";PWD=" & Password & ";Option=3;"
DBCONT.Open sConn
DBCONT.cursorlocation = 3
End Function
Public Function closeDatabase()
On Error Resume Next
DBCONT.Close
Set DBCONT = Nothing
On Error GoTo 0
End Function
以下代码有效:
Private Sub Workbook_Open()
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
Dim sqlstr As String
sqlstr = "SELECT * FROM Actor"
Call connectDatabase
rs.Open sqlstr, DBCONT
Dim actorfirstname As String
Dim actorlastname As String
Dim mysqlinsert As String
actorfirstname = InputBox("Enter first name")
actorlastname = InputBox("Enter last name")
mysqlinsert = "INSERT INTO Actor(first_name,last_name) VALUES ('" & actorfirstname & "','" & actorlastname & "')"
DBCONT.Execute mysqlinsert
If rs.RecordCount > 0 Then
For i = 1 To rs.RecordCount
For x = 1 To rs.Fields.Count
If i = 1 Then ThisWorkbook.Sheets("Sheet1").Cells(1, x).Value = rs.Fields(x - 1).Name
With ThisWorkbook.Sheets("Sheet1")
.Cells(i + 1, x).Value = rs(x - 1)
End With
Next x
rs.movenext
Next i
Else
MsgBox "No Records Found"
End If
rs.Close
Set rs = Nothing
Call closeDatabase
End Sub
以下代码不起作用...它出错了DBCONT.Execute sqlstrDelete行,运行时错误'-2147217900(80040e14)':自动化错误
Sub deleteRecord()
Dim sqlstrDelete As String
sqlstrDelete = "DELETE * FROM Actor WHERE last_name='TEST'"
Call connectDatabase
DBCONT.Execute sqlstrDelete
Call closeDatabase
End Sub
答案 0 :(得分:1)
*
DELETE * FROM Actor WHERE last_name='TEST'
这会执行吗?
DELETE FROM Actor WHERE last_name='TEST'