我正在编写一个宏,我希望从名为login的服务器表中删除表2中A列中的几个名称。
数据库名称是" my_db"和表名是登录。我调用连接来连接服务器数据库。以下是完整的代码: -
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim Sql As String
Sub Button1_Click()
Dim Ws As Worksheet
Dim Var As String
Dim i As Integer
i = 1
Set Ws = Worksheets("Sheet2")
Var = "login"
Sql = "name"
Call Connection
Do
Sql = " Delete From " & " " & Var & "" & " Where name" = "Ws.Cells(i, 1)"
Call Connection
i = i + 1
Loop Until Ws.Cells(i, 1) = ""
MsgBox "All entries deleted from login table"
End Sub
Dim strUserName As String
Dim strPassword As String
Dim ConnectString As String
Set cnt = New ADODB.Connection
strServerName = "localhost"
strDatabaseName = "my_db"
strUserName = "root"
strPassword = "root1"
ConnectString = "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=" & strServerName & _
";DATABASE=" & strDatabaseName & ";" & _
"USER=" & strUserName & _
";PASSWORD=" & strPassword & _
";OPTION=3;"
With cnt
.CursorLocation = adUseClient
.Open ConnectString
.CommandTimeout = 0
Set rst = .Execute(Sql)
End With
'rst.Close
'cnt.Close
Set rst = Nothing
Set cnt = Nothing
End Sub
但条目不会被删除。 SQL语法中有错误,任何人都可以帮助我使用sql语法吗?
答案 0 :(得分:1)
Sql = "delete From " & Var & " where name ='" & Ws.Cells(i, 1).Value & "'"
但最好只打开一次连接,运行所有删除,然后关闭连接。
此外,您不需要记录集(因为您没有返回任何记录),因此您可以忽略cnt.Execute
答案 1 :(得分:1)
由于您仅部分粘贴代码,我只能猜测。
Do
Sql = " Delete From " & Var & " Where name" = "Ws.Cells(i, 1)"
Call Connection (Sql)
i = i + 1
Loop Until Ws.Cells(i, 1) = ""
清理您的查询。更重要的是将它作为参数传递给连接。