How to connect an Oracle Database to Mathematica? - sql

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];

Related

Oracle SQL developer connect issue [duplicate]

I'm accessing an Oracle Database from a java application, when I run my application I get the following error:
java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region not found
You may also try to check the version of the Oracle jdbc driver and Oracle database. Just today I had this issue when using ojdbc6.jar (version 11.2.0.3.0) to connect to an Oracle 9.2.0.4.0 server. Replacing it with ojdbc6.jar version 11.1.0.7.0 solved the issue.
I also managed to make ojdbc6.jar version 11.2.0.3.0 connect without error, by adding oracle.jdbc.timezoneAsRegion=false in file oracle/jdbc/defaultConnectionProperties.properties (inside the jar). Found this solution here (broken link)
Then, one can add -Doracle.jdbc.timezoneAsRegion=false to the command line, or AddVMOption -Doracle.jdbc.timezoneAsRegion=false in config files that use this notation.
You can also do this programmatically, e.g. with System.setProperty.
In some cases you can add the environment variable on a per-connection basis if that's allowed (SQL Developer allows this in the "Advanced" connection properties; I verified it to work when connecting to a database that doesn't have the problem and using a database link to a database which has).
In a plain a SQL-Developer installation under Windows go to directory
C:\Program Files\sqldeveloper\sqldeveloper\bin
and add
AddVMOption -Duser.timezone=CET
to file sqldeveloper.conf.
Error I got :
Error from db_connection.java -->> java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region not found
ORA-00604: error occurred at recursive SQL level 1ORA-01882: timezone region not found
Prev code:
public Connection getOracle() throws Exception {
Connection conn = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:tap", "username", "pw");
return conn;
}
new Code:
public Connection getOracle() throws Exception {
TimeZone timeZone = TimeZone.getTimeZone("Asia/Kolkata");
TimeZone.setDefault(timeZone);
Connection conn = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:tap", "username", "pw");
return conn;
}
now it is working!!
Update the file oracle/jdbc/defaultConnectionProperties.properties in whatever version of the library (i.e. inside your jar) you are using to contain the line below:
oracle.jdbc.timezoneAsRegion=false
What happens is, that the JDBC client sends the timezone ID to the Server. The server needs to know that zone. You can check with
SELECT DISTINCT tzname FROM V$TIMEZONE_NAMES where tzname like 'Etc%';
I have some db servers which know about 'Etc/UTC' and 'UTC' (tzfile version 18) but others only know 'UTC' (tz version 11).
SELECT FILENAME,VERSION from V$TIMEZONE_FILE;
There is also different behavior on the JDBC client side. Starting with 11.2 the driver will sent the zone IDs if it is "known" to Oracle, whereas before it sent the time offset. The problem with this "sending of known IDs" is, that the client does not check what timezone version/content is present on the server but has its own list.
This is explained in Oracle Support Article [ID 1068063.1].
It seems it also depends on the Client OS, it was more likely that Etc/UTC fails with Ubuntu than RHEL or Windows. I guess this is due to some normalization but I haven't figured out what exactly.
in eclipse go run - > run configuration
in there go to JRE tab in right side panels
in VM Arguments section paste this
-Duser.timezone=GMT
then Apply - > Run
I had this problem when running automated tests from a continuous integration server. I tried adding the VM argument "-Duser.timezone=GMT" to the build parameters, but that didn't solve the problem. However, adding the environment variable "TZ=GMT" did fix it for me.
I ran into this problem with Tomcat. Setting the following in $CATALINA_BASE/bin/setenv.sh solved the issue:
JAVA_OPTS=-Doracle.jdbc.timezoneAsRegion=false
I'm sure that using one of the Java parameter suggestions from the other answers would work in the same way.
ERROR :
ORA-00604: error occurred at recursive SQL level 1 ORA-01882: timezone region not found
Solution:
CIM setup in Centos.
/opt/oracle/product/ATG/ATG11.2/home/bin/dynamoEnv.sh
Add this java arguments:
JAVA_ARGS="${JAVA_ARGS} -Duser.timezone=EDT"
In Netbeans,
Right-click your project -> Properties
Go to Run (under Categories)
Enter -Duser.timezone=UTC or -Duser.timezone=GMT under VM Options.
Click Ok, then re-run your program.
Note: You can as well set to other timestones besides UTC & GMT.
If this problem is in JDeveloper:
Change the project properties for both the model and the view project -> run/debug -> default profile -> edit
add the following run option:
-Duser.timezone=Asia/Calcutta
Make sure that the above time zone value is fetched from your database as follows:
select TZNAME from V$TIMEZONE_NAMES;
Along with that you'd want to check the time zone settings in your jdev.conf as well as in the JDeveloper -> Application Menu -> Default Project Propertes -> Run/Debug -> Default Profile -> Run Options.
I also same faced similar issue.
Environment:
Linux, hibernate project, ojdbc6 driver while querying oracle 11g database.
Resolution
TZ parameter was not set in linux machine, that basically tell oracle about the timezone.
So, After adding export statment "export TZ=UTC" at time of application start solved my problem.
UTC--> Change accorind to your timezone.
I had the same problem when trying to make a connection on OBIEE to Oracle db.
I changed my Windows timezone from (GMT+01:00) West Central Africa to (GMT+01:00) Brussels, Copenhagen, Madrid, Paris. Then I rebooted my computer and it worked just fine.
Seems like Oracle was not able to recognize the west central Africa timezone.
This issue happens as the code which is trying to connect to db, has a timezone which is not in db.
It can also be resolved by setting the time zone as below or any valid time zone available in oracle db.
valid time zone which can be found select * from v$version;
System.setProperty("user.timezone", "America/New_York");
TimeZone.setDefault(null);
I too had the same problem when i tried to create connection in JDeveloper. Our server located in different timezone and hence it raised the below errors as:
ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region not found
I referred many forums which asked to include timezone in the Java Options(Run/Debug/Profile) of Project properties and Default Project properties as -Duser.timezone="+02:00" bBut it didn't work for me. Finally the following solution worked for me.
Add the following line to the JDeveloper's configuration file (jdev.conf).
AddVMOption -Duser.timezone=UTC+02:00
The file is located in "<oracle installation root>\Middleware\jdeveloper\jdev\bin\jdev.conf".
In my case I could get the query working by changing "TZR" with "TZD"..
String query = "select * from table1 to_timestamp_tz(origintime,'dd-mm-yyyy hh24:mi:ss TZD') between ? and ?";
I was able to solve the same issue by setting the timezone in my linux system (Centos6.5).
Reposting from
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html
set timezone in /etc/sysconfig/clock e.g. set to ZONE="America/Los_Angeles"
sudo ln -sf /usr/share/zoneinfo/America/Phoenix /etc/localtime
To figure out the timezone value try to
ls /usr/share/zoneinfo
and look for the file that represents your timezone.
Once you've set these reboot the machine and try again.
Facing the same issue using Eclipse and a distant Oracle Database, changing my system time zone to match the time zone of the database server fixed the problem.
Re-start the machine after changing system time zone.
I hope this can help someone
java.sql.SQLException: ORA-00604: error occurred at recursive SQL
level 1 ORA-01882: timezone region not found
For this type of error, just change your system time to your country's standard GMT format
e.g. Indian time zone is chennai,kolkata.
Happens when you use the wrong version of OJDBC jar.
You need to use
11.2.0.4
For my case, i set the timezone at my OS level (ubuntu) with this command.
timedatectl set-timezone {timezone}
For example,
timedatectl set-timezone Africa/Kampala
This might be a bit late but It may help someone.
I encountered this issue while working on spring-boot application and failed to connect to the Oracle DB.
Error:
java.sql.SQLException: ORA-00604: error occurred at recursive SQL level 1
ORA-01882: timezone region not found
SELECT DBTIMEZONE FROM dual; -- This return: +00:00
timedatectl #The OS on the other hand returned correct time and timezone
Since I am not a system admin and not allowed to change system config, I had to apply a workaround in the codes.
spring.datasource.hikari.data-source-properties.oracle.jdbc.timezoneAsRegion=false
#Added the above into the application property file
The working solution came from the below link
Working solution URL
Edit
After the DBA patched the oracle with the missing timezone patches, The above (...timezoneAsRegion=false) was no longer needed.
For Spring-Boot Application - // add below two lines
#SpringBootApplication
public class Application {
public static void main(String[] args) {
// add below two lines
System.out.println("Setting the timezone"+TimeZone.getTimeZone("GMT+9:00").getID());
TimeZone.setDefault(TimeZone.getTimeZone("GMT+9:00"));
SpringApplication.run(Application.class, args);
}
}

Connect R to SQL Server in MAC

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)

SQL Editor of SAP HANA Vora Tools cannot connect with HANA

I try to show SAP HANA tables from SQL Editor of SAP HANA Vora Tools like below:
show tables
using com.sap.spark.hana
options
(
host "192.168.88.200",
instance "00",
port "30215",
user "SYSTEM",
passwd "Passw0rd",
dbschema "LEAGUE_SCHEMA"
);
but appears this error:
com.sap.spark.hana.client.HANAJdbcBadStateException:
[DefaultHANAConfiguration(192.168.88.200,00,30215,SYSTEM,Passw0rd,None)]
Cannot acquire a connection with error code 0, status ERROR_STATUS
Host, instance, port, user, passwd parameters are correct, and the dbschema is created in SAP HANA successfully.
What could be the error?
Thanks for the support!
Omit the 'port' parameter if it is not a multi-tenant HANA.
Have you verified from command line that you are able to ping and reach IP address 192.168.88.200?
Also, typically in HANA the SQL port is 3{InstanceNumber}15.
So in your case if the Instance is in fact 00, then the port should be 30015.
If you are working with tenant databases add the tenantdatabase parameter:
SHOW TABLES USING com.sap.spark.hana
OPTIONS (
host "a.b.c.d",
instance "90",
user "SYSTEM",
passwd "password",
tenantdatabase "SYSTEMDB",
dbschema "SYSTEM",
tablepattern "%"
);

Cannot connect to DB2 from Groovy

I’m trying to open an SQL instance within a driver which uses the DB2Driver from IBM.
The interesting part is that when I include:
def DB2Driver = new DB2Driver()
That initializes just fine.
But when I do
Sql.newInstance(info.getHost(), info.getConnectionMetaData().getParameterValue('username'), info.getConnectionMetaData().getParameterValue('password'), info.getConnectionMetaData().getParameterValue('driverClass'))
Or
Sql.newInstance(info.getHost(), info.getConnectionMetaData().getParameterValue('username'), info.getConnectionMetaData().getParameterValue('password'), 'com.ibm.db2.jcc.DB2Driver')
It will fail to open a SQL connection, saying that a suitable driver isn't found. How can I get the connection to DB2 to open?
Assuming that you are using a groovy script with #Grab and #Grapes annotations, you probably need configure Grape for JDBC drivers:
Because of the way JDBC drivers are loaded, you’ll need to configure Grape to attach JDBC driver dependencies to the system class loader
In groovy.sql.Sql the JDBC DriverManager is used to get a connection: DriverManager.getConnection(). Since it needs the driver depencencies attached to the system class loader, you need to do it with #GrabConfig.
For example, this script
#Grapes([
#Grab(group='org.hsqldb', module='hsqldb', version='2.3.2'),
])
import groovy.sql.Sql
def sql = Sql.newInstance('jdbc:hsqldb:mem:testdb', 'sa', '', 'org.hsqldb.jdbcDriver')
println 'SQL connection ready'
fails with the exception java.sql.SQLException: No suitable driver found for jdbc:hsqldb:mem:testdb, but with
#Grapes([
#Grab(group='org.hsqldb', module='hsqldb', version='2.3.2'),
#GrabConfig(systemClassLoader=true)
])
it works perfectly.

SQL Anywhere connection error: The driver doesn't support the version of ODBC behavior that the application requested

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.