Connecting to oracle database located remotely - oracle

I am trying to run following code which is connecting to remote database and retrieving records:
import java.sql.*;
class Employee
{
public static void main (String args [])
throws SQLException, ClassNotFoundException {
// Load the Oracle JDBC driver
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
// Connect to the database
// You must put a database name after the # sign in the connection URL.
// You can use either the fully specified SQL*net syntax or a short cut
// syntax as <host>:<port>:<sid>. The example uses the short cut syntax.
Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:#ourcompany.com:1521:course", "username", "password");
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select * from test");
// Iterate through the result and print the employee names
/*
while (rset.next ())
System.out.println (rset.getString ("name"));
System.out.println (rset.getString ("id"));
*/
rset.next();
System.out.println(rset.getString("name"));
}
}
after running this code from Netbeans i am getting an error:
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:#ourcompany.com:1521:course
at java.sql.DriverManager.getConnection(DriverManager.java:604)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at Employee.main(Emplyoee.java:23)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
I have downloaded ojdbc14.jar and kept in C:\Program Files\Java\jdk1.7.0\jre\lib path.
I do not know where i am going wrong?...plz help me here.

You are using awfully old version of Oracle JDBC driver. You should be using ojdbc6.jar.

Try with this driver:
Class.forName ("oracle.jdbc.OracleDriver");
Check your classpath in Netbeans:
How to set classpath in NetBeans:
In NetBeans Project Properties Window, you click Libraries in the left panel, and in the right panel are 4 categories of classpath you can configure:
Compile: Empty by default. Compile-time libraries are automatically
propagated to other categories of classpath, so you don't need to
repeat the same set of jar files in all 4 categories.
Run: By default includes everything in compile-time classpath, and
compiled classes (e.g., build/classes).
Compile Tests: By default includes everything in compile-time
classpath, compiled classes (e.g., build/classes), and JUnit.
Run Tests: By default includes classpath for compiling tests, and
compiled tests.

Related

Groovy java.sql.SQLException: No suitable driver found for jdbc:sqlserver://

I am quite new to groovy and am quite confused about the Groovy java.sql.SQLException that I'm getting.
Here is my code
// https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
#Grapes(
#Grab(group='com.microsoft.sqlserver', module='mssql-jdbc', version='7.2.2.jre8')
)
import groovy.sql.*
def username = xxx, password = yyy
// Create connection to MSSQL with classic JDBC DriverManager.
def db = Sql.newInstance("jdbc:sqlserver://localhost:1433;database=tempdb;", username, password, 'com.microsoft.sqlserver.jdbc.SQLServerDriver')
The same SQL JDBC Connection string ("jdbc:sqlserver://localhost:1433;database=tempdb;", 'com.microsoft.sqlserver.jdbc.SQLServerDriver') works just fine for my other cases, like Java or JMeter, but not works with groovy. This is what I'm getting:
> groovy groovy-sql-test.groovy
Picked up _JAVA_OPTIONS: -Xms512M -Xmx1g
Caught: java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost:1433;database=tempdb;
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost:1433;database=tempdb;
at groovy-sql-0.run(groovy-sql-0.groovy:11)
This is running under Win10.
I've also tried
groovy -cp D:\path\to\my\jars groovy-sql-test.groovy
where within the D:\path\to\my\jars dir, I'm having both sqljdbc41.jar and mssql-jdbc-7.2.2.jre8.jar files.
You have to use #GrabConfig(systemClassLoader=true) to use the system
classloader and thus get the jdbc driver picked up.
From https://groovy-lang.org/databases.html#_connecting_using_grab
The #GrabConfig statement is necessary to make sure the system
classloader is used. This ensures that the driver classes and system
classes like java.sql.DriverManager are in the same classloader.

Sybase JDBC connection login failed when run as WAR file; but login success when run within Eclipse

I am trying to connect to Sybase database from a Spring Boot application.
I am using JConnect jconn4 jdbc driver.
Login password is encrypted at Sybase server, so I am using bouncycastle cryptography API to encrypt the password.
Below is the block of code:
This code uses plain JDBC to test the connection, later I am planning to modify this to use Spring's JDBCTemplate.
Connection con = null;
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver");
logger.info("Loaded Sybase driver successfully.....");
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
and
String url = "jdbc:sybase:Tds:<url>:<port>/<databasename>";
Properties props = new Properties();
props.put("ENCRYPT_PASSWORD", "true");
props.put("JCE_PROVIDER_CLASS", "org.bouncycastle.jce.provider.BouncyCastleProvider");
props.put("user", "username");
props.put("password", "pwd");
and
con = DriverManager.getConnection(url, props);
When Login Success into Sybase Server:
Running the application within Eclipse IDE.
When Login failed into Sybase Server:
Running the generated WAR file within Windows command prompt.
Running the generated WAR file within Linux Shell (Dev/QA Server).
What I tried alreday:
1.Compared the version of jar file used by the application at runtime for the below jars.Because there are multiple versions of same jar file exists in classpath (from various dependencies).
jconn4-7.07.jar (sybase jdbc driver).
bcprov-jdk16-1.43.jar (bouncycastle crypto API).
I used below code block to find the jar used by the application at runtime.
Class clazz = null;
try {
clazz = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
logger.info("BouncyCastleProvider is ... " + clazz.toString());
if (clazz != null && clazz.getProtectionDomain() != null
&& clazz.getProtectionDomain().getCodeSource() != null) {
URL codeLocation = clazz.getProtectionDomain().getCodeSource().getLocation();
logger.info("BouncyCastleProvider jar is ... " + codeLocation.toString());
}
} catch (ClassNotFoundException e) {
logger.info(e.getMessage());
}
2.Found 4 versions of bcprov-jdk1x-x.xx.jar file through pom.xml's Dependency Hierarchy window in eclipse and 'excluded' three of those files in pom. This is to avoid version conflict of jar files.
but it is not working :-(.
Why it is able to connect within Eclispe and not while running as WAR?
Any help/direction would be much useful.
After a lot of research and spent almost 10 hrs of effort, I am able to solve this by adding 'CHARSET' into connection properties.
props.put("CHARSET", "iso_1");
Moral of the story: Problems may be bigger but solutions aren't :-).

Unable to connect to oracle database from groovy

Hi i am unable to connect to oracle database in groovy . I have used the following code in groovy console but getting the following compilation error
unable to resolve class oracle.jdbc.driver.OracleTypes
at line: 5, column: 1
I have used the following code
import java.sql.Connection
import java.sql.DriverManager
import javax.sql.DataSource
import groovy.sql.Sql
import oracle.jdbc.driver.OracleTypes
sql = Sql.newInstance("jdbc:oracle:thin:#localhost:1521:databasename",
"username", "password", "oracle.jdbc.OracleDriver")
If i remove import oracle.jdbc.driver.OracleTypes statement i am getting the following WARNING: Sanitizing stacktrace:.Kindly help me how to resolve this i have place ojdbc14.jar in the lib folder.
Remove all unnecessary imports and driver class from newInstance call as follows:
import groovy.sql.Sql
sql = Sql.newInstance("jdbc:oracle:thin:#localhost:1521:databasename", "username", "password")
The above is enough and works just fine for me, however I'm using ojdbc6-11.2.jar
Beside depends on if you are using SID or service name the last semicolon at JDBC URL might have to be changed for slash.
I had a few issues connecting Groovy to Oracle.
I tried grabbing ojdbc14.jar using
https://mvnrepository.com/artifact/com.oracle/ojdbc14/10.2.0.3.0
// https://mvnrepository.com/artifact/com.oracle/ojdbc14
#Grapes(
#Grab(group='com.oracle', module='ojdbc14', version='10.2.0.3.0')
)
but it did not find the file.
I copied ojdbc14.jar from my Oracle Client Directory to %GROOVY_HOME%\lib and it worked like a charm. I am sure you can download the ojdbc14.jar from the internet if you don't have the Oracle SQL Client Installed.
copy C:\DevSuiteHome_1\jdbc\lib\ojdbc14.jar C:\groovy-2.4.11\lib
url= "jdbc:oracle:thin:#localhost:1521:SID"
username = "un"
password = "pw"
driver = "oracle.jdbc.driver.OracleDriver"
// Groovy Sql connection test
import groovy.sql.*
sql = Sql.newInstance(url, username, password, driver)
try {
sql.eachRow('select sysdate from dual'){ row ->
println row
}
} finally {
sql.close()
}
Hope that helps.

How to connect Hive in iReport?

I am using Hadoop-0.20.0 and Hive-0.8.0. Now i have data into Hive table and i want generate reports from that. For that I am using iReport-4.5.0. For that I also download HivePlugin-0.5.nbm in iReport.
Now I am going to connect Hive connection in iReport.
Create New Data source --> New --> Hive Connection
Jdbc Drive: org.apache.hadoop.hive.jdbc.HiveDriver
Jdbc URl: jdbc:hive//localhost:10000/default
Server Address: localhost
Database: default
user name: root
password: somepassword
Then click on Test connection button.
I am getting error like:
Exception
Message:
java.lang.RuntimeException: org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: java.lang.RuntimeException: Illegal Hadoop Version: Unknown (expected A.B.* format)
Level:
SEVERE
Stack Trace:
org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException:
java.lang.RuntimeException: Illegal Hadoop Version: Unknown (expected A.B.* format)
org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:226)
org.apache.hadoop.hive.jdbc.HiveConnection.<init>(HiveConnection.java:72)
org.apache.hadoop.hive.jdbc.HiveDriver.connect(HiveDriver.java:110)
com.jaspersoft.ireport.designer.connection.JDBCConnection.getConnection(JDBCConnection.java:140)
com.jaspersoft.ireport.hadoop.hive.connection.HiveConnection.getConnection(HiveConnection.java:48)
com.jaspersoft.ireport.designer.connection.JDBCConnection.test(JDBCConnection.java:447)
com.jaspersoft.ireport.designer.connection.gui.ConnectionDialog.jButtonTestActionPerformed(ConnectionDialog.java:335)
com.jaspersoft.ireport.designer.connection.gui.ConnectionDialog.access$300(ConnectionDialog.java:43)
Can any one help me in this? Where i am wrong or missing something?
"I also download HivePlugin-0.5.nbm in iReport."
This isn't clear. iReport 4.5 has the Hadoop Hive connector pre-installed. Why did you download the connector separately? Did you install this plugin?
Create New Data source --> New --> Hive Connection
Jdbc Drive: org.apache.hadoop.hive.jdbc.HiveDriver
...
This isn't possible with the current Hadoop Hive connector. When you create a new "Hadoop Hive Connection" you are given only one parameter to fill out: the url.
I'm guessing that you created a JDBC connection when you meant to create a Hadoop Hive connection. This is a logical thing to do. Hive is accessed via JDBC. But the Hive JDBC driver is still pretty new. It has a number of shortcomings. That's why the Hive connector was added to iReport. It is based on the Hive JDBC driver, but it includes a wrapper around it to avoid some problems.
Or maybe you installed an old Hive connector over the top of the one that's already included with iReport 4.5. At some point in the past the Hive connector let you fill in extra information like the JDBC Driver.
Start with a fresh iReport installation, and make sure you use the Hadoop Hive Connection. That should clear it up.
The error "java.lang.RuntimeException: Illegal Hadoop Version: Unknown (expected A.B.* format)" happens because the VersionInfo class in hadoop-common.jar attempts to locate the version info using the current thread's class loader.
https://github.com/apache/hadoop/blob/release-2.6.0/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/VersionInfo.java#L41-L58
The code in question looks like this...
package org.apache.hadoop.util;
...
public class VersionInfo {
...
protected VersionInfo(String component) {
info = new Properties();
String versionInfoFile = component + "-version-info.properties";
InputStream is = null;
try {
is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(versionInfoFile);
if (is == null) {
throw new IOException("Resource not found");
}
info.load(is);
} catch (IOException ex) {
LogFactory.getLog(getClass()).warn("Could not read '" +
versionInfoFile + "', " + ex.toString(), ex);
} finally {
IOUtils.closeStream(is);
}
}
If your tool attempts to connect to the datasource in a separate thread, it will generate this error.
The easiest way to work around the issue is to put the hadoop-common.jar library in $JAVA_HOME/lib/ext or use the command line setting -Djava.endorsed.dirs to point to the hadoop-common.jar library. Then the thread's class loader will always be able to find this information.

class not found exception for com.mysql.jdbc.Driver not a classpath problem

I've been working on this for weeks, and now I'm just running in circles. I'm getting the runtime error: " class not found exception in [class] while getting connection com.mysql.jdbc.Driver ".
The connection function is as follows:
/**
* #return a MySQL connection to the server as specified above
*/
private static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
System.err.println("class not found exception in [class] while getting connection " + e.getMessage());
} catch (SQLException e) {
System.err.println("sql exception in [class] while getting connection " + e.getMessage());
}
return con;
} //end getConnection
I have set the $CLASSPATH a hundred times a hundred ways, and still no luck. This is what it looks like now:
# echo $CLASSPATH
:/usr/share/java/mysql-connector-java-5.1.13-bin.jar:/usr/share/java/mysql-connector-java-3.0.17-ga-bin.jar:
Both of those files exist and have the Driver.class file in them in the right place.
I even tried importing the class into my code before exporting the jar, but that caused a world of other problems.
I'm using Eclipse 3.5.2 and the server is running Fedora 13 x86_64
Please help.
edit: I'm running the code remotely on my server with the command:
# java -jar program.jar
Assuming you run it under Eclipse, try to add a reference to the jars in the Eclipse Run setting dialog.
Menu Run -> Run Configuration -> you project -> Classpath tab -> User Entries -> Add Jar...
If you are deploying on Apache Tomcat, place your JDBC connector jar file (mysql-connector-java-5.0.8-bin.jar) on lib folder of Tomcat home \apache-tomcat-6.0.29\lib\.
Some threads say its <tomcat_home>\common\lib\, but there is no common directory found on 6.0 in my case.
And don't forget to restart the server.
There is an easy way to solve this problem in Eclipse:
Right Click on your project
Select "Properties"
Select "Deployment Assembly"
Click Add -> "Java Build Path Entries"
Select your user library that contains your database connector (for example, mysql-connector-java-5.1.20.jar).
Problem has been fixed: I had to edit the manifest file to include the ClassPath: variable to the files I needed outside of eclipse, because eclipse does not allow an easy way to do it. When using JAR files, the classpath of the server doesn't matter, only that of the jar.
I found that I had to goto
Package Properties (Right click on project/package name and find Properties in the sub menu it might be at the bottom).
Java Build Path
Click the tab 'Order and Export'
Then tick the empty check box next to the library I wanted to include in the jar export.
(In my case it was ojdbc6.jar)

Resources