Node-odbc unable to connect to mssql - sql-server

I've spent the last day or two setting up unixODBC and freetds on ubuntu 12 - not a fun process in itself but it does now work using both sqsh and isql. I've installed node-odbc and I'm using the code snippet provided in the github readme to test the connection but I always get
S1000:1:0:[unixODBC][FreeTDS][SQL Server]Unable to connect to data source
WARNING: ev_unref is deprecated, use uv_unref
[Error: Error opening database]
Using isql I run isql -v SERVER user pass (using the correct creds..) and then use DATABASE once connected and it all works and I can run queries fine. My connection string in the js is
"DRIVER={FreeTDS};SERVER=SERVER;UID=user;PWD=pass;DATABASE=DATABASE"
Which exactly matches the credentials used for connecting with isql but in Node I get the aforementioned error. Any ideas on why this is happening? Is it possible that it's to do the location of my odbc.ini and odbcinst.ini files or something like that?
Just for reference:
/etc/odbc.ini:
[SERVER]
Driver = FreeTDS
Trace = No
Server = SERVER
Port = 1433
Database = DATABASE
UsageCount = 1
TDS_Version = 7.0
/etc/odbcinst.ini:
[FreeTDS]
Description = FreeTDS
Driver = /usr/lib/libtdsodbc.so
Setup = /usr/lib/libtdsS.so
FileUsage = 1
CPTimeout = 5
CPReuse = 20
Threading = 1
Thanks in advance for any help!

Ran into this problem today, it ended up being that I needed to specify a port number as part of the connection string. FYI.

It looks like I have just found a solution to this although I don't fully understand why. If the connection string used is:
"DRIVER={FreeTDS};SERVER=SERVER;UID=user;PWD=pass;DATABASE=DATABASE"
Then for some reason it doesn't work at all, I've tried using setting SERVER as both the IP and the actual name of the machine...no luck. However if I change the connection string to use SERVERNAME or DSN (can only have one of SERVER, SERVERNAME or DNS in the string) and I supply the machine name then it works fine, I can't get it to work with IP no matter what I try though. So, in summary the connection string that is working for me is:
"DRIVER={FreeTDS};SERVERNAME=SERVERNAME;UID=user;PWD=pass;DATABASE=DATABASE"
The key to this problem seems to lie in SQLDriverConnect.

Related

Python3: Connect to Remote Postgres Database with SSL

I am in the process of setting up a remote PostgreSQL database. The server is running CentOS 7 and PostgreSQL-9.5. Currently, I am testing whether users can query the database. To this end, I have the following:
import psycopg2
host = 'server1'
dbname = 'test_db'
user = 'test-user'
sslcert = 'test-db.crt'
sslmode = 'verify-full'
sslkey = 'test-db.key'
dsn = 'host={0} dbname={1} user={2} sslcert={3} sslmode={4} sslkey={5}'.format(host, dbname, user, sslcert, sslmode, sslkey)
conn = psycopg2.connect(dsn)
The connection times out with the following error:
psycopg2.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060)
Is the server running on host "server1" (xx.xx.xx.xx) and accepting
TCP/IP connections on port 5432?
I have tried several things (given below). I'm trying to pin down on which side the problem exists: the Python end or the database configuration:
Is the Python syntax correct?
Where can I find documentation concerning the DSN arguments, such as sslmode, sslcert, and sslkey?
Is there a different package better suited for this kind of connection?
What other questions should I be asking?
I have checked the following:
'server1' was entered correctly and the IP address returned by Python corresponds
All other arguments are spelled correctly and refer to the correct object
Postgres is currently running (service postgres-9.5 status shows "active")
Postgres is listening on port 5432 (netstat -na | grep tcp shows "LISTEN" on port 5432)
SSL is running for my table (psql -U username -W -d test-db -h host returns SSL connection (protocol: TLSAv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
user=test-user has been added to postgres as a Superuser
My understanding is that psycopg2 is the appropriate package to use nowadays. I have scoured the documentation and don't find much information regarding SSL connections. I found this SO post which talks about SSL connections using psycog2, but I can't match some of the syntax to the documentation.
In the Python script, I have tried the following in all 4 combinations:
Use sslmode='require'
Use absolute paths to test-db.crt and test-db.key
It appears that you have presented yourself with a False Dilemma. The problem does not lie solely between Python and the database configuration. There exist other entities in between which may cause a disconnect.
Is the Python syntax correct?
Yes. The syntax is described in the psycopg2.connect() documentation. It has the form:
psycopg2.connect(dsn=None, connection_factory=None, cursor_factory=None, async=False, **kwargs)
where the DSN (Data Source Name) can be given as a single string or as separate arguments:
conn = psycopg2.connect(dsn="dbname=test user=postgres password=secret")
conn = psycopg2.connect(dbname="test", user="postgres", password="secret")
Where can I find documentation concerning the DSN arguments, such as sslmode, sslcert, and sslkey?
Note that as DSN arguments, they are not part of the psycopg2 module. They are defined by the database, in this case Postgres. They can be found in the chapter on Database Connection Control Functions, under the Parameter Key Words section.
What other questions should I be asking?
Perhaps,
Is there anything between the host (the PostgresSQL server) and the client (the local Python instance) which could prevent communication?
One answer to this would be "the firewall." This turned out to be the problem. Postgres was listening and Python was reaching out. But the door was closed.

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!

How do I connect to an SQL server database in R

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.

Connecting R to an MS SQL database on a Mac using RODBC

I'm trying to connect to an MS SQL database from R (on a Mac) - after fiddling a lot with odbc.ini, odbcinst.ini, and installing freeTDS as described:
sudo port install freetds +mssql +odbc +universal
it now works on the Mac's command line level, but when trying to access it from R using the command:
con <- odbcConnect("myDSN", uid = "myID", pwd = "myPWD")
it just hangs and when forced to stop executing, I get 50+ of the following warnings:
In odbcDriverConnect("DSN=myDSN;UID=myID;PWD=myPWD") :
[RODBC] ERROR: state IM002, code 1421220112, message [iODBC][Driver Manager]Data source
name not found and no default driver specified. Driver could not be loaded
After having tried to make it work for about two days, I'm running out of suggestions. Can anybody help point me to what I am missing?
EDIT: It also works when running R on the virtual Windows machine. How do I get it to work on the Mac?
Did you first configure your MS SQL driver connection? If you have, then you should have a data source called "myDSN" in the OCBC Data Source dialog box.
Here is a great blog which gives step-by-step instructions and screen captures for what you need to do.
When you issue queries in R, R will try to talk to the ODBC data source called "myDSN". That data source knows what database you want (MS SQL) and also what the credentials (username/password) are needed to get access. This is the reason why you must configure the data source.

Stuck: SQL Server + Rails + Mac OS X

I am having an insanely tough time getting Rails to connect to SQL Server on a Mac.
I have set up a DSN using Actual SQL Server drivers: http://www.actualtech.com/ - it works great. I can test it and it seems to be functioning.
However, when I run:
iodbctest "dsn=rails_import2;uid=sa;pwd=mypassword"
The output is:
1: SQLDriverConnect = [Actual][SQL Server] Unable to connect to data source (0) SQLSTATE=S1000
1: ODBC_Connect = [Actual][SQL Server] Unable to connect to data source (0) SQLSTATE=S1000
I have been banging my head against the wall on this for hours. I have tried a lot of things and had it working at one point with FreeTDS +MSSQL (http://blog.opensteam.net/past/2009/1/28/rails_ms_sql_on_mac/), but it broke after a restart.
Any ideas?
So after a few days of mind-numbing experimentation, I've determined that I've somehow hosed my FreeTDS install. Not sure how, but I've basically given up on using the activerecord-sqlserver-adapter gem from my Mac.
The good news? The instructions here at http://odbc-rails.rubyforge.org/ work great. Oh, and you'll also need the activerecord-odbc-adapter gem.

Resources