How can I connect to oracle with jdbc from python? - java

Seeing the last part of this article, I'm dying to do the same on my Eclipse.
import jpype
import jaydebeapi
JHOME = jpype.getDefaultJVMPath()
jpype.startJVM(JHOME, '-Djava.class.path=/ojdbc8-full/ojdbc8.jar')
con = jaydebeapi.connect('oracle.jdbc.driver.OracleDriver','jdbc:oracle:thin:XXXXXX/XXXXXX#//99.99.99.99:1521/ABC')
cur = con.cursor()
cur.execute('select dummy from dual')
r = cur.fetchall()
print(r[0][0])
cur.close()
con.close()
And these message have appeard on my screen though, to tell the truth I have no knowledge about JAVA.
raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)
jpype._jexception.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class oracle.jdbc.driver.OracleDriver not found
So far, JAVA_HOME environment variable on my computer is the following.
java home
Since I don't know which jdbc driver is appropriate for my environment, I haven't actually done anything, he recommended downloading though.
And I don't know even where I should put that driver I would get later.
If someone tell me what I should do fast of all, I would be so happy! Thanks.

Related

Java 8 on Big Sur reports os.name as "Mac OS X" and os.version as "10.16"

Is it just my setup or is anyone else having this problem?
Using AdoptOpenJDK 1.8.0_275 installed at:
/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/jre
API docs of System.getProperties() do not specify any details.
Can confirm this is still happening on adoptopenjdk14, as well as openjdk early access build for j16.
You can file a bug if you want, but I bet it'll be denied. At this point, the name Mac OS X is not so much 'the name of the OS' as a 'globally agreed upon keyword identifying that unix-based mac operating system', where I mean globally literally (as in, 'around the planet', not 'across your source base/VM'). Changing it would just break stuff needlessly. The same applies, to a lesser degree, to version 10.16: The thing before the dot is not so much 'this is how the OS identifies itself' and more a 'globally agreed upon versioning scheme for Mac OS, identifying a wide and ill defined set of capabilities'.
There is no meaningful difference between the transition between big sur and catalina, other than the fact that apple made a marketing decision. If you want to point at an OS transition that might warrant the entirely nebulous choice to consider it a 'major change', surely it was the one to catalina, as that made by far the largest changes (including removing support for 32-bit entirely) in the last bunch of releases.
This leaves you with the challenge of: Okay, great, I can use System.getProperty("os.name") to get the globally agreed upon keyword that means unix-like Mac OS, and os.version for a string I can break into bits to figure out some nebulous batch of capabilities, but what if I need the actual name of the OS to e.g. show to a user?
Then you have three major options:
The easy one is to just write mapping code. Acknowledge that os.name and os.version give you (rather arguably) useful intent and not so much official names, and therefore, write some mappings. These would map name/version pairs to rendering strings, falling back to just printing the name string and the version string, concatenated, verbatim. You could add a mapping: Mac OS X/10.16 → Mac OS Big Sur in this table.
The hard way: Figure out you're on a mac (which is now easier; os.name returns Mac OS X, or just check for the existence: Files.isExecutable(Paths.get("/usr/bin/sw_vers"))), and then use ProcessBuilder to execute /usr/bin/sw_vers, picking up all output into a big string, and then parse it. Its output looks like:
ProductName: macOS
ProductVersion: 11.1
BuildVersion: 20C69
which, crucially, doesn't even include the words Big Sur, but does give you 11.1. I don't know how to run a command line tool that actually gives you Big Sur. Maybe system_profiler, but note that this takes many minutes to run, I really doubt you want to run that.
NB: you can also run .command("/usr/bin/sw_vers", "-productVersion") which gives you just 11.1, this may be a lot simpler to parse. -productName also works, gives you just macOS.
If you need this information to scan for OS capabilities, then stop doing this. It doesn't work with browsers, and it's not a good plan for OS releases either. What capability are you scanning for? Imagine, for example, if it is 'Can I run /usr/bin/sw_vers to figure stuff out', as a hypothetical example. The right strategy is NOT to check os.name/os.version, conclude that the command must exist, and then run it, failing catastrophically if it is not there. The right move is to check if /usr/bin/sw_vers exists, and then execute it, falling back to some non-mac based solution (perhaps /usr/bin/uname) in other cases. Scan for the capability, don't scan for the OS/version.
Java code to call native tool sw_vers
Regarding Option # 2 in the Answer by rzwitserloot, here is a complete code example to run from Java a command-line tool sw_vers that describes the version of macOS software running on the host computer.
If on the command-line (console) such as in Terminal.app, you run:
sw_vers
…in Big Sur on an Intel Mac we get:
ProductName: macOS
ProductVersion: 11.2
BuildVersion: 20D64
We only need the middle piece. So running:
sw_vers -productVersion
…shows simply 11.2, the value we need for your purpose.
Here is complete example app with a method to return this string into Java.
ProcessBuilder class creates operating system processes. Each new process is represented by the Process class.
We use try-with-resources syntax to automatically close the InputStream and Scanner objects.
Once you have the 11.2 string in hand, split on the FULL STOP, pull the first number 11, and you know you are running on Big Sur.
package org.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* Example code showing how to get current version of macOS from Java
* by running a native command-line tool `sw_vers`.
*/
public class App
{
public static void main ( String[] args )
{
App app = new App();
app.demo();
}
private void demo ( )
{
String version = this.getMacOsVersionNumber();
System.out.println( "version = " + version );
}
public String getMacOsVersionNumber ( )
{
String result = "";
List < String > command = List.of( "sw_vers" , " -productVersion" );
try (
InputStream inputStream = new ProcessBuilder( command ).start().getInputStream() ;
Scanner s = new Scanner( inputStream ).useDelimiter( "\\A" ) ;
)
{
result = s.hasNext() ? s.next() : "";
}
catch ( IOException e )
{
e.printStackTrace();
}
return Objects.requireNonNull( result );
}
}

Using SQLServer JDBC Driver in MATLAB

I need to connect to a SQLServer database from inside Matlab.
Caveats:
Buying licenses to Matlab's Database Toolbox is not an option-- I can only use core-Matlab and Java.
I cannot assume anything about the Java paths when Matlab is initialized.
Please don't tell me to use Python. I already know that but the company I work for does not...
Here's what I've done so far...
I've downloaded the SQL Server JDBC Driver from here.
I've created a sandbox directory, contents pictured below...
Here is my Matlab code.
% Connection params
server = 'myServerName';
port = 1433;
dbname = 'myDatabase';
user = 'user1';
pass = 'password';
url = sprintf('jdbc:sqlserver://%s:%d;DatabaseName=%s',server,port,dbname);
% Importing Java libraries
import java.sql.*;
import java.sql.DriverManager;
import java.sql.DriverManager.*;
% Add the Microsoft SQL Server JAR to Java path
javaaddpath('<path_to_this_folder>\sqljdbc41.jar'); %for JRE7
import com.microsoft.sqlserver.jdbc.*
% Try to instantiate the JDBC Driver
% This way DOES work
% (https://stackoverflow.com/questions/24438359/connecting-matlab-and-mysql-with-the-jdbc-driver)
if true
d = com.microsoft.sqlserver.jdbc.SQLServerDriver;
urlValid = d.acceptsURL(url);
props = java.util.Properties;
props.put('user',user);
props.put('password',pass);
con = d.connect(url, props);
% This way DOES NOT work.
%I referred to the sample code included with the JDBC to write this.
else
% Matlab Doc says this is similar to calling...
% Class.forName(...)
javaObjectEDT('com.microsoft.sqlserver.jdbc.SQLServerDriver');
driver = DriverManager.getDriver(url);
con = DriverManager.getConnection(url, user, pass);
end
It appears that for whatever reason, the DeviceManager is not loading the driver properly. The method DriverManager.getDriver(url) is throwing an Exception...
Java exception occurred:
java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(Unknown Source)
Is there a way to fix this or should I just roll with connecting directly through the Driver itself? I can't think of a reason why it matters. Will there be any consequences? Should I go with a DataSource approach instead?
Thanks!
You might want to try adding the driver to the static Java path rather than the dynamic Java path. Whenever I’ve worked with database drivers, they seem to have trouble if they’re on the dynamic path; I’m not sure why exactly, but they seem to need loading in a particular way that doesn’t work nicely if they’re on the dynamic path.

How do I find out why a java class in oracle is INVALID

I have a java class. I load it into Oracle 11 like this:
create or replace and compile java source named CubeTester as
import java.io.PrintWriter;
import java.io.StringWriter;
... etc
Oracle responds with "Statement Processed" -- so it looks like I did things right.. But when I do the SQL statement to find it's validity like this:
SELECT object_name, dbms_java.longname(object_name), status
FROM user_objects
WHERE object_type='JAVA CLASS'
AND dbms_java.longname(object_name) LIKE '%CubeTest%'
ORDER BY 1
I get this:
OBJECT_NAME DBMS_JAVA.LONGNAME(OBJECT_NAME) STATUS
CubeTester CubeTester INVALID
Now I went and checked every import that I have, and every one of them came back as VALID. (Except for the java.io.*, but as that is part of the JDK I assume that that is ok -- Am I wrong?)
And yes, the code works fine from eclipse (And command line too)
How does one debug this? The problem is that I am doing this from APEX (SQL Workshop), so I do not have access to the box, I can't use sqlplus or anything like that. It has to be a single SQL command or something.
Any suggestions on how to proceed?
try to use this sql command :
alter java class "Welcome" resolve;
may be this will solve your problem ,or gives you reason for errors

Java and R integration

I am trying to build a java project which contains R codes. Main logic behind that is I want to automate the data structuring and data analysis with in a same project. Partially I am being able to do that. I connected R to Java and my R codes are running well. I did all my set up in the local machine and its giving me all output as I need. As data set is big I am trying to run this on amazon server. But when I am shifting it to server, my project is not working properly. Its not being able to execute library(XLConnect), library(rJava). When ever I am calling this two libraries in my java project it's crashing. Independently in R codes are running and giving me output. What I can I for that, and how to fix thus error. Please help me out from this.
My java codes is
import java.io.InputStreamReader;
import java.io.Reader;
public class TestRMain {
public static void main(String[] arg)throws Exception{
ProcessBuilder broker = new ProcessBuilder("R.exe","--file=E:\\New\\Modified_Best_Config.R");
Process runBroker = broker.start();
Reader reader = new InputStreamReader(runBroker.getInputStream());
int ch;
while((ch = reader.read())!= -1)
System.out.print((char)ch);
reader.close();
runBroker.waitFor();
System.out.println("Execution complete");
}
}
And in the Modified_Best_Config.R I have written these codes
library('ClustOfVar');
library("doBy");
library(XLConnect)
#library(rJava)
#library(xlsx)
path="E:/New/";
############Importing and reading the excel files into R##############
Automated_R <- loadWorkbook("E:/New/Option_Mix_Calculation1.xlsx")
sheet1 <- readWorksheet(Automated_R, sheet = "Current Output")
sheet2 <- readWorksheet(Automated_R, sheet = "Actual Sales monthly")
sheet3 <- readWorksheet(Automated_R, sheet = "Differences")
#####################Importing raw Data###############################
optionData<- read.csv(paste(path,"ModifiedStructureNewBestConfig1.csv",sep=""),head=TRUE,sep=",");
nrow(optionData)
optionDemand=sapply(split(optionData,optionData$Trim),trimSplit);
optionDemand1=t(optionDemand[c(-1,-2),]);
optionDemand1
################Calculating the equipment Demand####################
optionDemand2<-t(optionDemand2[c(-1,0)]);
Rownames <- as.data.frame(row.names(optionDemand2))
writeWorksheet(Automated_R,Rownames, sheet = "Current Output", startRow = 21, startCol = 1)
writeWorksheet(Automated_R,optionDemand2, sheet = "Current Output", startRow = 21, startCol = 2)
saveWorkbook(Automated_R)
But java is stopping its operation after these line.
library("doBy");
Whole set of codes are running on nicely on my local machine. But whenever I am trying to run this on amazon server it's not running. Individually in R this code is running on server. I have couple of more R codes which are running with out any error. What can I do for that, please help me out.
Thanks for updating your question with some example code. I cannot completely replicate your circumstances because I presently don't have immediate access to Amazon EC2, and I don't know the specific type of instance you are using. But here a couple of suggestions for de-bugging your issue, which I have a hunch is being caused by a missing package.
1. Try to install the offending packages via your R script
At the very beginning of your R script, before you try to load any packages, insert the following:
install.packages(c("XLConnect", "rJava"))
If your instance includes a specified CRAN mirror (essentially, the online repository where R will first look to download the package source code from), this should install the packages in the same repo where your other packages are kept on your server. Then, either library or require should load your packages.
(sidenote: rJava is actually a dependency of XLConnect, so it will automatically load anyway if you only specify library(XLConnect))
2. If the above does not work, try installing the packages via the command line
This is essentially what #Ben was suggesting with his comment. Alternatively, see perhaps this link, which deals with a similar problem with a different package. If you can, in terminal on the server, I would try entering the following three commands:
sudo add-apt-repository ppa:marutter/rrutter
sudo apt-get update
sudo apt-get install r-cran-XLConnect
In my experience this has been a good go-to repo when I can't seem to find a package I need to install. But you may or may not have permission to install packages on your server instance.

How to make Java work with SQL Server?

I know this is a basic question, but I can't seem to find an answer and I apologize, if this question is way too stupid, but here we go:
I am supposed to work with SQL Server (no problem so far) and with Java (love java, so no problem here either), but now: What am I supposed to do to make the combination work?
I got: JRE 1.6 and the sqljdbc4.jar ... Before I put sqljdbc4.jar into my classpath I had sqljdbc.jar in it and with a test-program I got this exception:
21.08.2009 09:26:59 com.microsoft.sqlserver.jdbc.SQLServerConnection <init>
SCHWERWIEGEND: Die Java-Laufzeitumgebung (Java Runtime Environment, JRE), Version 1.6,
wird von diesem Treiber nicht unterstützt. Verwenden Sie die Klassenbibliothek
'sqljdbc4.jar', die Unterstützung für JDBC 4.0 bietet.
java.lang.UnsupportedOperationException: Die Java-Laufzeitumgebung (Java Runtime
Environment, JRE), Version 1.6, wird von diesem Treiber nicht unterstützt. Verwenden
Sie die Klassenbibliothek 'sqljdbc4.jar', die Unterstützung für JDBC 4.0 bietet.
at com.microsoft.sqlserver.jdbc.SQLServerConnection.<init>(SQLServerConnection.java:223)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:840)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at msSqlTest.DB.dbConnect(DB.java:13)
at msSqlTest.TestConnection.main(TestConnection.java:7)
Sorry for the German ... It basically means, that I should use sqljdbc4.jar, b/c the JRE I am using is not supported by the driver. So I put sqljdbc4.jar into my classpath, but it didn't work, so I am kinda lost, what I could do.
Maybe someone could tell be in an idiot-proof way what I should do :(
Oh yeah, here is the test appI use:
import java.sql.*;
public class TestConnection{
public static void main(String[] args){
// Neue DB und los geht's :)
DB db = new DB();
db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );
}
}
class DB{
public void dbConnect( String db_connect_string,
String db_userid,
String db_password){
try{
Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" );
Connection conn = DriverManager.getConnection(
db_connect_string,
db_userid,
db_password);
System.out.println( "connected" );
}
catch( Exception e ){
e.printStackTrace();
}
}
};
Have you tried the jtds driver for SQLServer?
Do not put both the old sqljdbc.jar and the new sqljdbc4.jar in your classpath - this will make it (more or less) unpredictable which classes are being used, if both of those JARs contain classes with the same qualified names.
You said you put sqljdbc4.jar in your classpath - did you remove the old sqljdbc.jar from the classpath? You said "it didn't work", what does that mean exactly? Are you sure you don't still have the old JAR in your classpath somewhere (maybe not explicitly)?
The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.
http://msdn.microsoft.com/en-us/library/ms378526.aspx
sqljdbc4.jar class library requires a
Java Runtime Environment (JRE) of
version 6.0 or later.
I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).
Maybe a little late, but using different drivers altogether is overkill for a case of user error:
db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );
should be either one of these:
db.dbConnect("jdbc:sqlserver://localhost\muff", "user", "pw" );
(using named pipe) or:
db.dbConnect("jdbc:sqlserver://localhost:1433", "user", "pw" );
using port number directly; you can leave out 1433 because it's the default port, leaving:
db.dbConnect("jdbc:sqlserver://localhost", "user", "pw" );
For anyone still googling this, go to \blackboard\config\tomcat\conf and in wrapper.conf put an extra line in wrapper.java.classpath pointing to the sqljdbc4.jar and then update the wrapper.conf.bb as well
Then restart the blackboard services and tomcat and it should work
It won't work by simply setting your java classpath, you have to set it up in the blackboard config files to point to your jar file with the jdbc library
I had the same problem with a client of my company, the problem was that the driver sqljdbc4.jar, tries a convertion of character between the database and the driver. Each time that it did a request to the database, now you can imagine 650 connections concurrently, this did my sistem very very slow, for avoid this situation i add at the String of connection the following parameter:
SendStringParametersAsUnicode=false, then te connection must be something like url="jdbc:sqlserver://IP:PORT;DatabaseName=DBNAME;SendStringParametersAsUnicode=false"
After that, the system is very very fast, as the users are very happy with the change, i hope my input be of same.
Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).
I used 1.5 for the other server, so I waisted a lot of time on this.
Tricky issue.
If you are use sqljdbc4.jar, use the following code
ResultSet objResultSet = objPreparedStatement.getResultSet();
if (objResultSet == null) {
boolean bResult = false;
while (!bResult){
if (objPreparedStatement.getMoreResults()){
objResultSet = objPreparedStatement.getResultSet();
bResult = true;
}
}
}
objCachedRowSet = new CachedRowSetImpl();
objCachedRowSet.populate(objResultSet);
if (CommonUtility.isValidObject(objResultSet)) objResultSet.close();
objResultSet = null;
What about the official JDBC 4.0 compatible JDBC driver from Microsoft?

Categories

Resources