我真的是Excel宏和VBA的新手。我想做的是使用宏从MySQL数据库获取数据。我搜索将Excel连接到MySQL的代码,就得到了这个
Sub connect()
Dim Password As String
Dim SQLStr As String
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
Dim table_name As String
Set rs = CreateObject("ADODB.Recordset")
Server_Name = ""
Database_Name = ""
User_ID = ""
Password = ""
table_name = ""
Set cn = CreateObject("ADODB.Connection")
cn.Open "Driver={MySQL ODBC 5.1 Unicode Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
SQLStr = ""
rs.Open SQLStr, cn, adopenstatic
ThisWorkbook.Sheets(1).Range("A1").CopyFromRecordset rs
cn.Close
MsgBox "DONE!"
End Sub
我更改了一些代码以匹配我的系统
Sub connect()
Dim Password As String
Dim SQLStr As String
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
Dim table_name As String
Set rs = CreateObject("ADODB.Recordset")
Server_Name = "localhost"
Database_Name = "sakila"
User_ID = "root"
Password = "Password"
table_name = ""
Set cn = CreateObject("ADODB.Connection")
cn.Open "Driver={MySQL ODBC 8.0 Unicode Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
SQLStr = "select * from film_actor"
rs.Open SQLStr, cn, adopenstatic
ThisWorkbook.Sheets(1).Range("A2").CopyFromRecordset rs
cn.Close
MsgBox "DONE!"
End Sub
它可以很好地用于这样的查询,但是当我尝试将查询更改为
SQLStr = "select a.title, concat(b.first_name, Space(1),b.last_name), c.name, a.description, a.rating from film_actor z"
left join film a on a.film_id = z.film_id
left join actor b on b.actor_id = z.actor_id
left join film_category y on y.film_id = z.film_id
left join category c on c.category_id = y.category_id
order by a.title asc"
它始终显示“预期:声明结尾” ,并在左连接的第一个连接处突出显示“电影” 单词,并且还有一个黄色箭头也突出显示'Sub第一行中的connect()'。我已经在'film_actor z'之后删除了引号,但它又回来了。我的查询/代码有什么问题吗?
答案 0 :(得分:1)
尝试这样的事情:
SQLStr = "select a.title, concat(b.first_name, Space(1),b.last_name), c.name, a.description, a.rating from film_actor z" & _
" left join film a on a.film_id = z.film_id" & _
" left join actor b on b.actor_id = z.actor_id" & _
" left join film_category y on y.film_id = z.film_id" & _
" left join category c on c.category_id = y.category_id" & _
"order by a.title asc"