簡體   English   中英

如何用R連接數據庫

[英]How to connect database with R

我在使用sqlQuery將數據庫與R連接時遇到問題。

library(RODBC)
res =sqlQuery(channel,
    paste0("select pb.col1,pb.col2 from pb,
                   mp,fb,st 
            where fb.col10 in ('%s',input), 
            and fb.col20=mp.col30 
            and pb.col40=st.col50 
            and pb.col45=st.col60 
            and mp.col40=pb.col80 and 
            pb.col80=st.col90"),
         believeNRows=F)

在這里, input=c("abc","def","wvy","etz") ,但是實際輸入具有超過10,000個字符串元素。

已經設置了與數據庫連接的通道。

子句似乎存在一些問題,但我不知道如何解決。

誰能幫我這個?

paste0無法按照您使用它的方式工作。 您將需要使用:

sprintf("select pb.col1,pb.col2 
         from pb,mp,fb,st 
            where fb.col10 in %s 
            and fb.col20=mp.col30 
            and pb.col40=st.col50 
            and pb.col45=st.col60 
            and mp.col40=pb.col80 and 
            pb.col80=st.col90", input)

接下來,您采用這種結構化的方式將導致query參數為向量。 您應該以將query作為單個字符串為目標。

使用RODBCext可能會更好

library(RODBCext)
res =sqlExecute(channel,
              "select pb.col1,pb.col2 
               from pb,mp,fb,st 
               where fb.col10 in ?, 
                  and fb.col20=mp.col30 
                  and pb.col40=st.col50 
                  and pb.col45=st.col60 
                  and mp.col40=pb.col80 
                  and pb.col80=st.col90",
              data = list(c("abc", "def", "wvy", "etz")),
              fetch = TRUE,
              stringsAsFactors = FALSE)

最后,我不確定此查詢是否有效的SQL語法。 也許我弄錯了,但是我不認為您可以像在此處那樣在FROM子句中列出多個表。 如果您需要多個表,則應采用某種方式將它們聯接在一起。

FROM Table1 LEFT JOIN Table2 ON Table1.ID = Table2.Ref

編輯:我剛剛看到您的input具有10,000多個元素,這將使sqlExecute相當慢。 您確定LIKE是查詢這些數據的最佳方法。 如果可能的話,我建議使用其他方法隔離所需的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM