How do I connect to an SQL server database in R - sql-server

I'm trying to connect to the SQL Sever database using R but not sure on the details for the query string. I normally use SQL server management studio on SQL Server 2008 and connnect using single sign on. I found the below example
myconn <- odbcDriverConnect(connection="Driver={SQL Server
Native Client 11.0};server=hostname;database=TPCH;
trusted_connection=yes;")
I get the below warning message
Warning messages:
1: In odbcDriverConnect(connection = "Driver={SQL Server \nNative Client 11.0};server=hostname;database=TPCH;\ntrusted_connection=yes;") :
[RODBC] ERROR: state IM002, code 0, message [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
2: In odbcDriverConnect(connection = "Driver={SQL Server \nNative Client 11.0};server=hostname;database=TPCH;\ntrusted_connection=yes;") :
ODBC connection failed
How do I go about finding the specifics i need?

I have done this in the past with an odbc named connection that I've already had in place. In case you don't know, you can create one in windows by typing into the search prompt 'odbc' and selecting "set up data sources". For example - if you named an odbc connection 'con1' you can connect the following way:
con<-odbcConnect('con1') #opening odbc connection
df<-sqlQuery(con, "select *
from ssiD.dbo.HOURLY_SALES
") #querying table
close(con)

This works for me.
library(RODBC)
dbconnection <- odbcDriverConnect("Driver=ODBC Driver 11 for SQL Server;Server=server_name; Database=table_name;Uid=; Pwd=; trusted_connection=yes")
initdata <- sqlQuery(dbconnection,paste("select * from MyTable;"))
odbcClose(channel)
Also, see these links.
RODBC odbcDriverConnect() Connection Error
https://www.simple-talk.com/sql/reporting-services/making-data-analytics-simpler-sql-server-and-r/

The problem is simpler than this. The big clue is the \n in the error message. Something has re-flowed your connection string such that there is now a new-line character in the driver name. That won't match any registered driver name. Pain and suffering then ensues. Make sure your whole connection string is on a single line!
I often use:
driver={SQL Server Native Client 11.0}; ...
and it works really well. Much better than having to rely on pre-defined connection names.

Try another ODBC driver.
In windows press the "windows" button and then type "odbc".
Click the "Data sources (ODBC)" link.
Go to the "Drivers" tab to see the available drivers for SQL Server.
Also - remove the " " spaces after the semicolons in your connection string.
Note - the database property should point to a database name rather than a table name.
This worked for me:
odbcDriverConnect("Driver=SQL Server Native Client 11.0;Server=<IP of server>;Database=<Database Name>;Uid=<SQL username>;Pwd=<SQL password>")

First, you need to install the package 'RSQLServer', and all its dependencies.
Then execute the following command in RStudio, with relevant parameters:
conn <- DBI::dbConnect(RSQLServer::SQLServer(),
server = '<server>',
port = '<port>',
properties = list(
user = '<user>',
password = '<password>'
))
Finally, db_list_tables(conn) gives you the list of tables in the corresponding database.

Related

pyodbc - using try: except to detect if connection not made

I'm new at pyodbc and I'm using the following code to connect my database:
(IDE is VS Code) I'm testing the connection to ensure that an error message is displayed if I fail to connect to the server:
All is fine if the server name is correct, but if I deliberately misspell the server name in order to prove that the connection is not successful, then the code appears to hang. (VSC shows code still running and I need to manually click on Stop), so then I don't appear to reach the try/except statement.
import pyodbc
try:
conn = pyodbc.connect(Trusted_Connection='yes', driver = '{SQL Server}',server = 'xxx-xxxx\SQLEXPRESS' , database = 'master')
except pyodbc.Error as ex:
print(ex)
else:
print('Connected')
print('Done')
Thanks all
Russ

Not able to use RSQLserver

I am trying to use RSQLServer and first installed RSQLServer using R studio. then I am trying to use it like this.
library(RSQLServer)
library(DBI)
drv <- dbDriver("SqlServer")
conn <- dbConnect(drv, url = "Server=**MYSERVERURL;database=DBName;trusted_connection=yes;")
res <- dbSendQuery(conn, "SELECT TOP 100 * FROM test_table (NOLOCK)")
str(res)
But I am getting error everytime. Am I missing something? The Error is Object not found.? Do I need to configure any driver (probably jTDS) first? If yes, can anyone share steps to do that? Thanks.
Error text
> conn <- dbConnect(drv, url = "Server=**MYSERVERURL;database=DBName;trusted_connection=yes;")
Error in dbConnect(drv, url = "Server=**MYSERVERURL;database=DBName;trusted_connection=yes;") :
object 'drv' not found
> res <- dbSendQuery(conn, "SELECT TOP 100 * FROM test_table (NOLOCK)")
Error in dbSendQuery(conn, "SELECT TOP 100 * FROM test_table (NOLOCK)") :
object 'conn' not found
> str(res)
Error in str(res) : object 'res' not found
Note: name of table and database changed.
Try to use
drv <- RSQLServer::SQLServer()
instead of
drv <- dbDriver("SqlServer")
You must have downloaded and installed the jTDS driver.
For Windows authentication you have to install a DLL too:
If you intend to use integrated security (Windows Authentication) to
authenticate your server session, you will need to download jTDS and
copy the native single sign on library (ntlmauth.dll) to any
location on your system’s PATH (e.g. Sys.getenv("PATH") ).
Source: https://cran.r-project.org/web/packages/RSQLServer/RSQLServer.pdf
Your JDBC connection string looks strange, please make sure your JDBC connection string is correct.
If you are using the jTDS driver the connection string syntax is
different from the JDBC driver of Microsoft
The jTDS syntax is specified here:
http://jtds.sourceforge.net/faq.html#urlFormat
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
where is "sqlserver".
The Microsoft JDBC syntax is specified here but I think it does not work because RSQLServer is based on the cross-platform jTDS JDBC driver
https://msdn.microsoft.com/en-us/library/ms378428(v=sql.110).aspx
Example:
jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;
Replace the "localhost" part with the IP address or server name like "myServer.honey.moon.com", in case of a non-standard IP port (not 1433) of the instance use "localhost:1234".
You can figure out the IP port by looking at the connection string you use to connect to the database via SQL Server Management Studio!

What is the difference between these two SQL Server connection strings

When I use the following connection strings, the first one is working and the second is not working on my system. May I know the difference between these two connections strings?
DSN=ABCD;DATABASE=db1;UID=userid;PWD=passwd
and the second one
Data Source=ABCD;DATABASE=db1;UID=userid;PWD=passwd
Error thrown by second string
[unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)
I am new to using SQL Server, so confused the difference between DSN and Data Source
There can be many reasons as to why your second connection string is not working. You need to check Why do I get error "Data source name not found and no default driver specified"?
The ODBC Driver Manager relies on the Driver attribute to know which
ODBC driver to load.
Data source (in Data Source=ABCD) is not a valid connection keyword. See the connection properties here.
In the first connection string DSN is an odbc DataSource name. If it works it means you have one configured.
In the second one Data Source is the sever name not the DSN.
For additional reference :
DSN connection strings
SQL Server connection string

Having trouble connecting to SQL Server database from VBA using ADO connection

I want to connect to a SQL Server database without using DSN. I'm receiving an error when trying to connect to said database. The error is
Run-time error '-2147467259 (80004005)': [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
My connection string looks like this:
"ODBC;DRIVER=SQL Server;SERVER=lokdb; UID=secret;PWD=secret;APP=Microsoft Open Database Connectivity;WSID=" & Environ$("COMPUTERNAME") & ";Network=DBMSSOCN;Trusted_Connection=Yes;DATABASE=EDMS-Lok"`
I am able to connect to the default database on the server with the credentials specified if I remove the DATABASE=EDMS-Lok parameter from the connection string, however I don't then seem to be able to "find" the EDMS-Lok database. E.g. if I try using
SELECT * FROM EDMS-Lok.dbo.eng_dwg
I get an error message
Run-Time error '-2147217900 (80040e14)': [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '-'
(eng_dwg is a valid table)
When I connect without specifying a database, the .DefaultDatabase property of the ADO connection object returns "020" which I don't even see as an available database on that server??
When connected, if I use SELECT name FROM sys.databases I'm able to get a list of the databases available. They are:
010
100
500
EDMS-Lok
Master
msdb
MSLLockDB
pubs
tempdb
I got it working using DSN, but I don't want to use DSN.
Not sure what is wrong here??
I would say the problem is that you mix up the authentication models. You provide user + password but also you have configured trusted connection = yes. I'm not sure how ADO works in that case but I would assume that it doesn't use the configured user and connects with the windows account. Delete the trusted connection parameter in the connection string and try again.
OK, credit for this answer should go to Dee and Sam who commented on the original question, however I can't mark a comment as the answer, so here it is:
Needed to wrap the database name in square brackets [ ] ... like this DATABASE=[EDMS-Lok] - (credit to DEE)
I first tried wrapping the database name in the connection string i.e. DATABASE=[EDMS-Lok] and this did not work (same error). However, if I connect without specifying the database, I'm able to access the table using SELECT * FROM [EDMS-Lok].dbo.eng_dwg
It didn't work in the connection string because the string is not T-SQL code. To get it to work, you may need to figure out how to escape the dash character. – (credit to SAM)
I've tried single and double quotes, backslash, square brackets, parentheses and curly brackets and nothing seems to work to escape the hyphen in the database name within the connection string. But, since I can now access the database and the tables I need, which was the original question, I wanted to mark it as answered.

Remove login prompt with SQL linked tables in Access

I have an issue similar to this one: SQL Server 2008: ODBC connection problems
But mine is unique because I already have the "Save Password" option checked when I link my tables, AND it works fine unless I try to open more than one query at a time.
Steps to recreate:
1) Link a SQL table to an Access 2003 front-end, my DSN looks like this:
[ODBC]
DRIVER=SQL Server
UID=ACD
WSID=ACD
APP=ACD
SERVER=xx.xx.xxx.xx,1053
Description=ACD Connection to SQL Server
Pwd=XXXXXXXX
At first I didn't have the PWD line, it doesn't seem to make a difference with or without that.
2) Open 1 query that uses the linked table, no login prompt
3) Open 2nd query while first one still open, get this error followed by login prompt:
[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed.
The login is from an untrusted domain and cannot be used with Windows authentication.
I can open as many tables as I want directly and I don't get a password prompt.
If I login once, no more prompts until I restart Access, but this isn't an option for my app.
I'm using SQL server auth only, not setup for Windows auth.
You could try using a DSN-Less connection to your SQL server, microsft have a support page for this: http://support.microsoft.com/kb/892490
This should stop the prompts
You have to save the password in you connection (see parameter dbAttachSavePWD)
Dim MyTable As TableDef
Set MyTable = CurrentDb.CreateTableDef(TableName, dbAttachSavePWD, SourceTableName, ConnectionString)
CurrentDb.TableDefs.Append MyTabl
for example to attach sql table [audit].[Details] as AuditDetails you can use the following code:
Dim MyTable As TableDef
Set MyTable = CurrentDb.CreateTableDef
(
"AuditDetails",
dbAttachSavePWD,
"audit.Details",
"ODBC;DRIVER={SQL Server};APP=TransFlow®;SERVER=sqlServerName;DATABASE=dbName;UID=userName;PWD=password"
)
CurrentDb.TableDefs.Append MyTabl

Resources