RODBC: able to connect to db but can't find table object - r

I am trying to connect SQLite database using RODBC in R. RODBC is able to connect to the database but is not able to get the list of tables in database using sqlTables, which returns "0 rows". The database has 20 tables.
System: R 3.1.2, Windows 7, Rstudio
Code snippet
> library(RODBC)
> odbcGetInfo(bbdb1)
DBMS_Name
"SQLite"
DBMS_Ver
"3.8.6"
Driver_ODBC_Ver
"03.00"
Data_Source_Name
"bbdb1"
Driver_Name
"sqlite3odbc.dll"
Driver_Ver
"0.999"
ODBC_Ver
"03.80.0000"
Server_Name
"C:\\Users\\shals\\Documents\\R in a nutshell\\nutshell\\data\\bb1"
> sqlListTables(bbdb1)
Error: could not find function "sqlListTables"
> sqlTables(bbdb1)
[1] TABLE_CAT TABLE_SCHEM TABLE_NAME TABLE_TYPE REMARKS
<0 rows> (or 0-length row.names)
> sqlPrimaryKeys(bbdb1,func,errors=FALSE,as.is=TRUE,catalog=NULL,schema=NULL)
Error in sqlPrimaryKeys(bbdb1, func, errors = FALSE, as.is = TRUE, catalog = NULL, :
object 'func' not found
Can anyone please help why sqlTables returning 0 rows when there are 20 tables in database.

changed the connection string as below after which the code worked fine.
bbdb1 <- odbcConnect(dsn="bbdb",believeNRows = FALSE,rows_at_time = 1)

Related

How can I reduce the error of SQL query in R?

Here is my function
getSQL <- function(server="server name", database="database name", Uid="
user name", Pwd="password", Query){
conlink <- paste('driver={SQL Server};server=', server,';database=',database,';Uid=', Uid,
';Pwd=', Pwd,';Encrypt=True;TrustServerCertificate=False', sep="")
conn <- odbcDriverConnect(conlink)
dat <- sqlQuery(channel= conn, Query, stringsAsFactors = F)
odbcCloseAll()
return(dat)
}
When I call the function using
query.cut = "SELECT [measurename]
,[OrgType]
,[year_session]
,[Star]
,[cutvalue]
,[Date]
,[File]
FROM [database name].[dbo].[DST_Merged_Cutpoint]
ORDER BY [year_session] DESC
"
getSQL(Query=query.cut)
I get this error:
Error in sqlQuery(conn, Query, stringsAsFactors = F) :
first argument is not an open RODBC channel
In addition: Warning messages:
1: In odbcDriverConnect(conlink) :
[RODBC] ERROR: state 28000, code 18456, message [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user ' insightm8'.
2: In odbcDriverConnect(conlink) :
[RODBC] ERROR: state 01S00, code 0, message [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute
3: In odbcDriverConnect(conlink) :
Error in sqlQuery(conn, Query, stringsAsFactors = F) :
first argument is not an open RODBC channel
How can I fix these errors? Thanks in advance
Take care not to add spaces to UID:
Server]Login failed for user ' insightm8'.
Reproducing this on an SQL Server connection creates the same error.
Try using paste0 instead of paste :
conlink <- paste0('driver={SQL Server};server=', server,';database=',database,';Uid=', Uid,
';Pwd=', Pwd,';Encrypt=True;TrustServerCertificate=False', sep="")

Can't get data with dbplyr from shiny-server

I'm trying to get data from AWS SQL Server.
This code works fine from local PC, but it didn't work from shiny-server (ubuntu).
library(dbplyr)
library(dplyr)
library(DBI)
con <- dbConnect(odbc::odbc(),
driver = "FreeTDS",
server = "aws server",
database = "",
uid = "",
pwd = "")
tbl(con, "shops")
dbGetQuery(con,"SELECT *
FROM shops")
"R version 3.4.2 (2017-09-28)"
packageVersion("dbplyr")
[1] ‘1.2.1.9000’
packageVersion("dplyr")
[1] ‘0.7.4’
packageVersion("DBI")
[1] ‘0.7.15’
I have next error:
tbl(con, "shops")
Error: <SQL> 'SELECT *
FROM "shops" AS "zzz2"
WHERE (0 = 1)'
nanodbc/nanodbc.cpp:1587: 42000: [FreeTDS][SQL Server]Incorrect syntax near 'shops'.
But dbGetQuery(con,"SELECT * FROM shops") works fine.
Can you explain what's going wrong?
This is more likely because the FreeTDS driver does not return the class that dbplyr expects to see in order to use the MS SQL translation. The workaround is to take the result of class(con) and then add the following lines right after you connect, but before calling tbl(). Replace the [you class name] with the results of the class(con) call:
sql_translate_env.[your class name] <- dbplyr:::`sql_translate_env.Microsoft SQL Server`
sql_select.[your class name]<- dbplyr:::`sql_select.Microsoft SQL Server`

How to store SparkR Dataframe in cassandra?

head(users)
1 jay chennai
2 kumar bangalore
3 vinoth Trichy
4 saswath perambalur
I want to store this output to cassandra table . I tried the below lines to store
users.write
.format("org.apache.spark.sql.cassandra")
.options(Map( "table" -> "sparkusers", "keyspace" -> "bigdata"))
.save()
throws error
unexpected symbol in test.write.format("org.apache.spark.sql.cassandra").options" please help me on this?
You are using the wrong syntax for R (That is the python/scala syntax)
read.df(sqlContext, source = "org.apache.spark.sql.cassandra", keyspace = "ks", table = "table")
See Spark R Dataframe Documentation

'Con not a connection' Error in R program

I am trying to use readLines in R but I am getting below error
orders1<-readLines(orders,2)
# Error in readLines(orders, 2) : 'con' is not a connection
Code :
orders<-read.csv("~/orders.csv")
orders
orders1<-readLines(orders,2)
orders1
Data:
id,item,quantity_ordered,item_cost
1,playboy roll,1,12
1,rockstar roll,1,10
1,spider roll,1,8
1,keystone roll,1,25
1,salmon sashimi,6,3
1,tuna sashimi,6,2.5
1,edamame,1,6
2,salmon skin roll,1,8
2,playboy roll,1,12
2,unobtanium roll,1,35
2,tuna sashimi,4,2.5
2,yellowtail hand roll,1,7
4,california roll,1,4
4,cucumber roll,1,3.5
5,unagi roll,1,6.5
5,firecracker roll,1,9
5,unobtanium roll,1,35
,chicken teriaki hibachi,1,7.95
,diet coke,1,1.95
I'm guessing you want this:
orders1 <- readLines( file("~/orders.csv") )
It's not clear why you want to do your own parsing or substitution, but that should give readLines a valid connection object.

I cannot connect postgresql schema.table with dplyr package

Im trying to connect postgres with dplyr functions
my_db <- src_postgres(dbname = 'mdb1252', user = "diego", password = "pass")
my_db
src: postgres 9.2.5 [postgres#localhost:5432/mdb1252]
tbls: alf, alturas, asociad, atenmed, base, bfa_boys_p_exp, bfa_boys_z_exp,
bfa_girls_p_exp, bfa_girls_z_exp, bres, c21200012012, c212000392011, c212000532011,
c21200062012, c212006222012, c212007352012, c212012112013, c212012242012,
c212012452012, c2222012242012, calles, cap, cap0110, casos_tbc_tr09, casos_tbctr09,
casosvadela, catpo, cbcvl, cie09, cie10, cie103d, cie103dantigua, cie10c, cie9a,
cie9mc, clasiarc, coalc, coddepto, codedades, codest, codlocaerbio, codprov, coheb,
cohec, cohep, cohiv, coho09_20110909_m, coign, combl, comet, comp, comport, conev,
conymad, copri, corci3cod, corci910, cores, corin, cotab, cutoi, cutto, def0307,......
but when I try to connect a tbl
my_tbl <- tbl(my_db, 'def0307')
Error in postgresqlExecStatement(conn, statement, ...) :
RS-DBI driver: (could not Retrieve the result : ERROR: no existe la relación «def0307»
LINE 1: SELECT * FROM "def0307" WHERE 0=1;
^
)
I think the problem is a schema issue because sql should be:
SELECT * FROM mortalidad.def0307
I made my_tbl <- tbl(my_db, 'mortalidad.def0307');
my_tbl <- tbl(my_db, c('mortalidad','def0307')) without a solution.
Im having a lot of fun working with dplyr Im from SQL but I wish resolve that and trying dplyr skills.
Thanks in advance.
Finally dplyr has the solution to this problem thanks to the latest version 0.7 recently announced by Hadley Wickham. The DBI and dbplyr libraries greatly simplified the connection between dplyr and PostgreSQL.
con <- DBI::dbConnect(RPostgreSQL::PostgreSQL(),
host = "database.rstudio.com",
user = "hadley",
password = rstudioapi::askForPassword("Database password"))
tbl <- dplyr::tbl(con, dbplyr::in_schema('mortalidad','def0307'))
You might want this,
db=src_postgres(dbname = 'mdb1252',
user = "diego", password = "pass", options="-c search_path=mortalidad")
If anybody ends up here with the same problem, here is what works for me: (taken from #Diego's comment from Feb 6'14)
postgre_table <- function (src, schema, table) {
paste('SELECT * FROM', paste(schema, table, sep = '.')) %>%
sql() %>% tbl(src = src)
}

Resources