I want to connect R to SQL Server on my MAC (El Capitan), I can do it very easy in Python, but in R I can't do it.
In Python it is easy as:
import pymssql
pymssql.connect(server = 'CHWN-DSX-DB02', user = 'XXXX',password ='XXXX',database = 'Info')
For R, I tried with RODBC library, but didn't work, I think the problem is the "Driver":
driver.name <- "SQL Server"
db.name <- "Info"
host.name <- "CHWN-DSX-DB02"
port <-""
server.name <-"XXX"
pwd <- "XXX"
# Use a full connection string to connect to a SAMPLE database
con.text <- paste("DRIVER=",RMySQL::MySQL(),
";Database=",db.name,
";Server=",host.name,
";Port=",port,
";PROTOCOL=TCPIP",
";UID=", server.name,
";PWD=",pwd,sep="")
con1 <- odbcDriverConnect(con.text)
This code in R never ends, and when I stop it, I have this warning:
Warning messages:
1: In odbcDriverConnect(con.text) :
[RODBC] ERROR: state 00000, code 0, message [iODBC][Driver Manager]dlopen(SQL Server, 6): image not found
There are several issues with your current setup:
General vs. Specific APIs: In Python you are using a specific SQL Server API: pymssql. In fair comparison to your R attempt, you should be using the ODBC API: pyodbc (to compare with RODBC). Remember there are multiple ways to connect to backend databases or data stores from client applications either by specific APIs or generalized APIs (ODBC, OLEDB, JDBC, etc.).
Required Drivers: To use any ODBC library be it Python, R, or other language, you need to have an installed ODBC driver on your client machine. Download such drivers before attempting connection. Nearly every RDBMS or data store maintains (usually free to download) ODBC drivers for Windows, Mac, and Linux OS's including SQL Server: 2013 or 2017.
Mixing R Libraries: In R, most APIs follow the DBI standard including ROracle, RJDBC, odbc, RMySQL, RPostgreSQL, RSQLite. Unfortunately, RODBC does not follow this standard. Your attempted connection appears to be an attempted DBI connection using the RMySQL::MySQL() object which even in DBI is not part of an ODBC connection string.
Note even though both require underlying ODBC drivers (see #2), RODBC is a different library and implementation than odbc. Additionally, do not conflate specific APIs such as RMySQL with an attempted general SQL Server ODBC. In fact, it is unclear why you use RMySQL when you have a variable for driver.name. Also such a value, 'SQL Server' is the Windows ODBC driver name and not macOS or Linux names. See below R ODBC connections:
RODBC
driver.name <- "ODBC Driver 13 for SQL Server" # REQUIRES DOWNLOAD
driver.name <- "ODBC Driver 17 for SQL Server" # REQUIRES DOWNLOAD
...
con.text <- paste0("driver=", driver.name,
";database=", db.name,
";server=", host.name,
";port=", port,
";protocol=TCPIP",
";UID=", user.name,
";PWD=", pwd)
conn <- odbcDriverConnect(con.text)
odbc
conn <- dbConnect(odbc::odbc(), driver = driver.name,
server = host.name, port = port, database = db.name
uid = user.name, pwd = pwd)
# ALTERNATIVE:
conn <- dbConnect(odbc::odbc(), .connection_string = con.text)
Related
import pyodbc
connection = pyodbc.connect('Driver = {SQL Server};Server=SIWSQL43A\SIMSSPROD43A;'
'Database=CSM_reporting;Trusted_Connection=yes;')
Error:
connection = pyodbc.connect('Driver = {SQL Server};Server=SIWSQL43A\SIMSSPROD43A;'
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Do not put a space after the Driver keyword in the connection string.
This fails on Windows ...
conn_str = (
r'DRIVER = {SQL Server};'
r'SERVER=(local)\SQLEXPRESS;'
r'DATABASE=myDb;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
... but this works:
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=(local)\SQLEXPRESS;'
r'DATABASE=myDb;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
I am also getting same error. Finally I have found the solution.
We can search odbc in our local program and check for version of odbc. In my case I have version 17 and 11 so. I have used 17 in connection string
'DRIVER={ODBC Driver 17 for SQL Server}'
I'm using Django 2.2
and got the same error while connecting to sql-server 2012. Spent lot of time to solve this issue and finally this worked.
I changed driver to
'driver': 'SQL Server Native Client 11.0'
and it worked.
I've met same problem and fixed it changing connection string like below.
Write
'DRIVER={ODBC Driver 13 for SQL Server}'
instead of
'DRIVER={SQL Server}'
Local Ms Sql database server need or {ODBC driver 17 for SQL Server}
Azure Sql Database need{ODBC driver 13 for SQL SERVER}
Check installed drivers here => Installed ODBC Drivers
Format for connection to Azure Sql Database is :
import pyodbc
conn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};'
'SERVER=tcp:nameServer.database.windows.net,1433;'
'DATABASE=Name database; UID=name; PWD=password;')
Format for connection to Ms SQL Databse Local:
import pyodbc
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=server.name;' // example Doctor-Notebook\\MSSQLEXPRESS
'DATABASE=database.name; Trusted_connection = yes')
I faced this issue and was looking for the solution. Finally I was trying all the options from the https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Windows , and for my MSSQL 12 only "{ODBC Driver 11 for SQL Server}" works. Just try it one by one. And the second important thing you have to get correct server name, because I thought preciously that I need to set \SQLEXPRESS in all of the cases, but found out that you have to set EXACTLY what you see in the server properties. Example on the screenshot:
You could try:
import pyodbc
# Using a DSN
cnxn = pyodbc.connect('DSN=odbc_datasource_name;UID=db_user_id;PWD=db_password')
Note: You will need to know the "odbc_datasource_name". In Windows you can search for ODBC Data Sources. The name will look something like this:
Data Source Name Example
The below code works magic.
SQLALCHEMY_DATABASE_URI = "mssql+pyodbc://<servername>/<dbname>?driver=SQL Server Native Client 11.0?trusted_connection=yes?UID" \
"=<db_name>?PWD=<pass>"
Below connection string is working
import pandas as pd
import pyodbc as odbc
sql_conn = odbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER=SERVER_NAME;DATABASE=DATABASE_NAME;UID=USERNAME;PWD=PASSWORD;')
query = "SELECT * FROM admin.TABLE_NAME"
df = pd.read_sql(query, sql_conn)
df.head()
I have had the same error on python3 and this help me:
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=YourServerName;'
'DATABASE=YourDatabaseName;UID=USER_NAME;PWD=PASS_WORD;')
remember python is case-sensitive so you have to mention DRIVER,SERVER,... in upper case.
and you can visit this link for more information:
https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver15
In my case, the exact same error was caused by the lack of the drivers on Windows Server 2019 Datacenter running in an Azure virtual machine.
As soon as I installed the drivers from https://www.microsoft.com/en-us/download/details.aspx?id=56567, the issue was gone.
for error : pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
No space between the driver and event
connection = Driver={SQL Server Native Client 11.0};
"Server=servername;"
"Database=dbname;"
"Trusted_Connection=yes;"
Apart from the other answers, that considered the connection string itself, it might simply be necessary to download the correct odbc driver. My client just faced this issue when executing a python app, that required it.
you can check this by pressing windows + typing "odbc".
the correct driver should appear in the drivers tab.
Create a DSN something like this (ASEDEV) for your connection and try to use DSN instead of DRIVER like below:
enter code here
import pyodbc
cnxn = pyodbc.connect('DSN=ASEDEV;User ID=sa;Password=sybase123')
mycur = cnxn.cursor()
mycur.execute("select * from master..sysdatabases")
row = mycur.fetchone()
while row:
print(row)
row = mycur.fetchone()`
I was facing the same issue whole day wasted and I tried all possible ODBC Driver values
import pyodbc
connection = pyodbc.connect('Driver = {SQL Server};Server=ServerName;'
'Database=Database_Name;Trusted_Connection=yes;')
In place of Driver = {SQL Server} we can try these option one by one or just you can use with you corresponding setting, somehow in my case the last one works :)
Driver={ODBC Driver 11 for SQL Server} for SQL Server 2005 - 2014
Driver={ODBC Driver 13 for SQL Server} for SQL Server 2005 - 2016
Driver={ODBC Driver 13.1 for SQL Server} for SQL Server 2008 - 2016
Driver={ODBC Driver 17 for SQL Server} for SQL Server 2008 - 2017
Driver={SQL Server} for SQL Server 2000
Driver={SQL Native Client} for SQL Server 2005
Driver={SQL Server Native Client 10.0} for SQL Server 2008
Driver={SQL Server Native Client 11.0} for SQL Server 2012
You need to download Microsoft ODBC Driver 13 for SQL Server
from Microsoft ODBC Driver 13
Thank you Avinash.
brilliant. I tried to connect to MS Azure database using PyCharm. It worked.
server = ''
database = ''
username = ''
password = ''
driver = 'SQL Server Native Client 11.0'
connection1 = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password + ';TDS_Version=8.0')
print("Connected.")
Try below:
import pyodbc
server = 'servername'
database = 'DB'
username = 'UserName'
password = 'Password'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Tbl')
for row in cursor:
print('row = %r' % (row,))
Have you installed any product of SQL in your system machine ?
You can download and install "ODBC Driver 13(or any version) for SQL Server" and try to run if you havent alerady done.
Make sure you have all drivers and db engine installed
https://www.microsoft.com/en-us/download/details.aspx?id=54920
server = '123.45.678.90'
database = 'dbname'
username = 'username'
password = 'pwork'
driivver = '{ODBC Driver 17 for SQL Server}'
samgiongzon='DRIVER='+driivver+';SERVER='+server+\
';DATABASE='+database+';UID='+username+\
';PWD='+password+';Trusted_Connection=no;'
pyodbc.connect(samgiongzon, autocommit=True)
it worked for me; you need to install driver from here
https://learn.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver15
or (in ubuntu) sudo apt-get install unixodbc-dev if you get an error with pip install pyodbc
if any one are trying to access the database which is hosted in azure then try to give the driver as ODBC Driver 17 for SQL Server
I have created an ODBC connections (both 32/64 bit) with configuration given below:
Microsoft SQL Server ODBC Driver Version 10.00.14393
Data Source Name: ODBCMSSQL
Data Source Description:
Server: .\SQLEXPRESS
Database: MedicalMarketting
Language: (Default)
Translate Character Data: Yes
Log Long Running Queries: No
Log Driver Statistics: No
Use Regional Settings: No
Prepared Statements Option: Drop temporary procedures on disconnect
Use Failover Server: No
Use ANSI Quoted Identifiers: Yes
Use ANSI Null, Paddings and Warnings: Yes
Data Encryption: No
I want to connect to local MsSQL server as given in below code snippet:
string connectionString = "Data Source=ODBCMSSQL;Initial Catalog=MedicalMarketting;Integrated Security=True";
con = new OdbcConnection(connectionString);
cmd = new OdbcCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
try
{
this.con.Open();
this.tr = con.BeginTransaction();
this.cmd.Transaction = tr;
}
catch (Exception ex)
{
this.RollBack();
}
This throws an exception which has an error message as below:
ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Sorry if this was too basic, but had to post for a clue because the same configuration for different ODBC connections works perfectly.
I found a quick fix to the problem by changing the connection string to,
string connectionString = "DSN=ODBCMSSQL";// best practice is to store this in a seperate config file.
In fact, other attributes specified (Initial Catalog, Integrated Security) are not ODBC connection string attributes, hence ignored. A full list of ODBC connection attributes can be found below.
https://msdn.microsoft.com/en-us/library/ee275047(v=bts.10).aspx
I use the following specs to connect to db from Matlab and it works:
% Matlab code
spec.dbName = 'xxxyyy';
spec.login = 'uid';
spec.pwd = 'mypwd';
spec.driver = 'net.sourceforge.jtds.jdbc.Driver';
spec.url = 'jdbc:jtds:sqlserver://vmsqlprod7:1234/xxxyyy';
conn = database(spec.dbName, spec.login, spec.pwd, spec.driver, spec.url);
I'm almost sure this is all I need to connect from R. But I can't seem to make it work with the following code:
## R code
require(RODBC)
con <- odbcDriverConnect(connection=
"driver=net.sourceforge.jtds.jdbc.Driver;
server=jdbc:jtds:sqlserver://vmsqlprod7:1234/xxxyyy;
database=xxxyyy;
uid=uid;
pwd=mypwd")
It throws out this error:
[ODBC Driver Manager] Data source name not found and no default driver specified
I've read this and I suspect it's about the format of the url or driver string, but I don't know exactly how to make it recognizable by R.
I can really use some help here!
Environment: Windows 7, 64 bit.
R version: 3.3.3
I'm trying to connect to a SQL Anywhere 5 database (I know it's olllld!) with a .NET 3.5 app in WinXP and it works fine from a stand alone console app. But when I run the exact code in a plugin ,running off a separate AppDomain, (the only difference I can tell between the two) with the following code, I get the errors further below.
BTW Both are executed as the SAME user.
using (OdbcConnection connection =
new OdbcConnection(strConnect))
{
OdbcCommand command = new OdbcCommand(query, connection);
command.CommandType = CommandType.Text;
DataTable posRecordsTable = new DataTable();
connection.Open();
OdbcException Exception returns the following errors:
Index #0
Message: [Sybase][ODBC Driver]Unable to connect to database server: database engine not running
Index #1
Message: [Sybase][ODBC Driver]Invalid connection string attribute
Index #2
Message: [Sybase][ODBC Driver]Invalid connection string attribute
Index #3
Message: [Microsoft][ODBC Driver Manager] The driver doesn't support the version of ODBC behavior that the application requested (see SQLSetEnvAttr).
Does the driver on your AppDomain have the same configuration as your stand alone box? I think checking the similarity of the environments will help you. Usually such errors are resolved by looking at the config files from where the driver reads its information. Dont know much about SQL Anywhere, but in general, I've come across such issues and I fixed them by altering the connection information or the configuration file.
I am trying to connect an Oracle database to Mathematica 8. Another question already says how it can be done in for a MySQL database but it does not work for me:
Needs["DatabaseLink"] AND conn = OpenSQLConnection[JDBC["MySQL(Connector/J)",
"yourserver/yourdatabase"], "Username" -> "yourusername", "Password" -> "yourpassword"]
The following information is available for me on my desktop:
filepath = "C:\oracle\ora92\network\ADMIN\tnsnames.ora"; HOST; PORT; username; password;
conn = OpenSQLConnection[JDBC["MySQL(Connector/J)", HOST], "Username" -> username, "Password" -> password]
Error message: JDBC::error:
Communications link failure The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server. >>
Does anyone know how I can connect or continue?
Mathematica 8 does not come pre-equipped with an Oracle driver, a fact that can be verified by evaluating these expressions:
Needs["DatabaseLink`"]
JDBCDriverNames[]
(*
Out[2]= {Microsoft Access(ODBC),hsqldb,HSQL(Memory),HSQL(Server),
HSQL(Server+TLS),HSQL(Standalone),HSQL(Webserver),HSQL(Webserver+TLS),
jtds_sqlserver,jtds_sybase,mysql,MySQL(Connector/J),ODBC(DSN),odbc,
PostgreSQL,Microsoft SQL Server(jTDS),Sybase(jTDS),HSQL 2.0.1}
*)
We will have to follow the instructions in the Mathematica documentation that describes how to install a new JDBC driver.
First, we will have to create a new resource directory in which to place the necessary JDBC driver JAR file:
$jarDirectory =
CreateDirectory #
FileNameJoin #
{$UserBaseDirectory, "Applications", "Oracle", "Java"}
Next, we must select a JDBC driver to use. Visit the relevant Oracle page to find the correct JDBC driver for your database.
Chose a driver version that is compatible with Java 6, the version that Mathematica 8 uses internally. For this example, I chose to use the Oracle 11.2.0.2.0 driver for Java 6. Download the file and then move it into the resource directory just created:
SystemOpen[$jarDirectory]
Next, we will create a JDBC driver configuration file so that the new driver is registered with Mathematica:
$configDirectory =
CreateDirectory #
FileNameJoin #
{$UserBaseDirectory, "Applications", "Oracle", "DatabaseResources"}
Export[
FileNameJoin # {$configDirectory, "Oracle.m"}
, JDBCDriver[
"Name" -> "Oracle"
, "Driver" -> "oracle.jdbc.driver.OracleDriver"
, "Protocol" -> "jdbc:oracle:thin:#"
, "Version" -> 1
]
, "Text"
]
The driver is now installed:
JDBCDriverNames[]
(*
Out[9]= {Oracle,Microsoft Access(ODBC),hsqldb,HSQL(Memory),HSQL(Server),
HSQL(Server+TLS),HSQL(Standalone),HSQL(Webserver),HSQL(Webserver+TLS),
jtds_sqlserver,jtds_sybase,mysql,MySQL(Connector/J),ODBC(DSN),odbc,
PostgreSQL,Microsoft SQL Server(jTDS),Sybase(jTDS),HSQL 2.0.1}
*)
If the fates are smiling, we can now establish a connection and execute an SQL query:
$connection =
OpenSQLConnection[
JDBC["Oracle", "myserver:1521:mysid"]
, "Username" -> "scott"
, "Password" -> "tiger"
]
SQLExecute[$connection, "SELECT 'success!' FROM DUAL"]
... where myserver is the database server name, 1521 is the listener port number and mysid is the Oracle System ID (SID).
Oracle JDBC URLs come in many forms. For details, take a look at the Oracle FAQ.
I suspect that you are using the wrong JDBC driver - you should be using the Oracle JDBC driver, rather than MySQL one. When I was using DatabaseLink to connect to an Oracle database, I used this command:
OpenSQLConnection[
JDBC[
"oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:#server:port:dbname"
],
"Name" -> "dbname",
"Username" -> "YourUserName",
"Password" -> "YourPassword"
]
You should make sure to put the proper Oracle JDBC driver (corresponding to your Oracle db version) into a place where Mathematica can find it. This procedure is described in the documentation for the DatabaseLink, section JDBC Connections. You can test which JDBC drivers are visible to Mathematica by executing JDBCDrivers[]. Make sure that you install and use the correct driver corresponding to your DB version, b.t.w. - incorrect driver versions may result in very nasty and non-obvious bugs (this is unrelated to Mathematica).
My guess would be that you shouldn't use MySQL JBDC connections for Oracle. Although it is for Mathematica 5.2, here is an article that you perhaps can use as something to go from.
I've barely used Mathematica, and certainly not with a database, but from that page, it looks like you can do this:
OpenSQLConnection[JDBC["oracle","server.business.com:1999"],
Username -> "you"]
Whilst the answer from WReach above is correct it may also be helpful to know that there are 2 additional lines that are useful - namely to make sure Jlink is loaded and the Java ClassPath is correct and pointing to your oracle jdbc6.jar file.
Needs["JLink`"]
AddToClassPath[
FileNameJoin[{$UserBaseDirectory, "Applications", "Oracle",
"Java"}]];
or if using the answer verbatim just
Needs["JLink`"]
AddToClassPath[$jarDirectory];