java.lang.ClassNotFoundException: com/microsoft/sqlserver/jdbc/SQLServerDriver - java

I am really new to JAVA but need to call a SQL Server function which I have been given access to.
I have built a JAVA call into a pl/sql function and am successfully calling it from one of my environments. When I move to another environment I get the error
ORA-29532: Java call terminated by uncaught Java exception: java.lang.ClassNotFoundException: com/microsoft/sqlserver/jdbc/SQLServerDriver
I have researched this to death and checked the correct installation of JAVA which seems fine but I'm obviously missing something. I need to somehow trace what is different on this environment, the fact that it runs in the other envionmnet proves that the class is correct so it has to be a config issue.
JAVA Class
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.net.Socket;
import java.io.IOException;
public class xxiceHJ
{
protected static String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
protected static String DB_URL = "jdbc:sqlserver://999.999.99.99:1433";
protected static String USER = "xxxx";
protected static String PWD = "xxxxx123$";
public static String getOrderStatus (String OrderNumber) throws SQLException, Exception
{
Connection conn = null;
CallableStatement cs = null;
ResultSet rs = null;
String Message = null;
String WarehouseId = "01";
try
{
// Register JDBC driver
Class.forName(JDBC_DRIVER);
//Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PWD);
cs = conn.prepareCall("{call usp_get_order_status(?,?,?)}");
cs.setString(1, WarehouseId);
cs.setString(2, OrderNumber);
cs.setString(3, Message);
rs = cs.executeQuery();
//if prodeure return a value
if (rs.next())
{
Message = rs.getString(1);
}
//Clean-up environment
rs.close();
cs.close();
conn.close();
// }
// catch (SQLException se)
// {
// //Handle errors for JDBC
// cfFileNumber = "SQLException" + se.toString();
// se.printStackTrace();
// }
// catch (Exception e)
// {
// //Handle errors for Class.forName
// cfFileNumber = "Exception" + e.toString();
// e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if (rs!=null)
{
rs.close();
}
}
catch (SQLException se2)
{
//nothing we can do
}
try
{
if (cs!=null)
{
cs.close();
}
}
catch (SQLException se2)
{
//nothing we can do
}
try
{
if (conn!=null)
{
conn.close();
}
}
catch (SQLException se)
{
se.printStackTrace();
}
}
return Message;
}
}

The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer. If the drivers are not listed in your CLASSPATH variable, you receive the following error message when you try to load the driver:
java.lang.ClassNotFoundException: com/microsoft/jdbc/sqlserver/SQLServerDriver
The JDBC driver is not part of the Java SDK. If you want to use it, you must set the classpath to include the sqljdbc.jar file or the sqljdbc4.jar file. If the classpath is missing an entry for sqljdbc.jar or sqljdbc4.jar, your application will throw the common "Class not found" exception.
The sqljdbc.jar file and sqljdbc4.jar file are installed in the following location:
\sqljdbc_\\sqljdbc.jar
\sqljdbc_\\sqljdbc4.jar
The following is an example of the CLASSPATH statement that is used for a Windows application:
CLASSPATH =.;C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc.jar
The following is an example of the CLASSPATH statement that is used for a Unix/Linux application:
CLASSPATH =.:/home/usr1/mssqlserverjdbc/Driver/sqljdbc_4.0/enu/sqljdbc.jar
You must make sure that the CLASSPATH statement contains only one Microsoft JDBC Driver for SQL Server, such as either sqljdbc.jar or sqljdbc4.jar.
For more information, please see:
http://support.microsoft.com/kb/313100
http://msdn.microsoft.com/en-us/library/ms378526.aspx

first Please download correct sql driver and then check your are using correct connection driver as per operating system. then once you have to test your connection if its working fine then you will go to next .
so please check this url
microsift sql server driver for linux
https://msdn.microsoft.com/en-us/library/hh568451(v=sql.110).aspx
my sql server driver for linux
https://dev.mysql.com/downloads/connector/j/5.0.html

Related

Why does executeUpdate() function not work? Give steps to solve in a normal project rather than a maven based project [duplicate]

This question already has an answer here:
Caused by: java.lang.NoSuchMethodError: org.postgresql.core.BaseConnection.getEncoding()Lorg/postgresql/core/Encoding;
(1 answer)
Closed 4 years ago.
CODE:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aaa;
import static aaa.DB.geom;
import static aaa.DB.getConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] argv) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
// Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres", "postgres",
"abc");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
//Connection conn = getConnection();
connection.setAutoCommit(false);
Statement s = null;
try {
s = connection.createStatement();
} catch (Exception e) {
System.out.println("statmnt connection not works");
}
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ss.executeUpdate();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
String query = "CREATE TABLE COMPANY(ID INT );";
ResultSet r = s.executeQuery(query);
connection.commit();
} else {
System.out.println("Failed to make connection!");
}
}
}
RUN:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
You made it, take control your database now!
Exception in thread "main" java.lang.NoSuchMethodError:
org.postgresql.core.BaseConnection.getPreferQueryMode()Lorg/postgresql/jdbc/PreferQueryMode;
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:151)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
at aaa.JDBCExample.main(JDBCExample.java:69)
C:\Users\Dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
QUESTION:Give me steps to solve it since database is connected already! What is the core of the problem?
The problem is that if database postgresql connected then why not insert into database. The tables are also available and seen from netbeans. There needs to be a way to solve this run time exception issue when there is a query execution... So I needed step by step details to make it correct.
A SELECT statements has to be executed using executeQuery(). executeUpdate() is for DML statements like UPDATE, INSERT, or DELETE that don't normally return a ResultSet. Also, a DDL statement like CREATE TABLE can not be executed using executeQuery() you need execute() or executeUpdate() for that.
So your code should be:
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ResultSet rs = ss.executeQuery();
while (rs.next() {
// do something
}
rs.close();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
And:
String query = "CREATE TABLE COMPANY(ID INT );";
s.execute(query);
connection.commit();
You have connection.setAutoCommit(false); and you didnt commit after performing update. You have to commit your transaction in order for changes to apply. You can also setAutoCommit(true);

Connect Java to remote DB2 from neatbeands

I'm trying to do a small application that take some data from a db by connecting to a remote DB2 server using following example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionExample
{
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50000/exampledb";
String user="db2inst1";
String password="password";
Connection connection = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
I get this error:
com.ibm.db2.jcc.am.SqlException: [jcc][10389][12245][3.67.27] Errore nel caricamento della libreria nativa db2jcct2, java.lang.UnsatisfiedLinkError: no db2jcct2 in java.library.path: ERRORCODE=-4472, SQLSTATE=null
further infromation here:
http://www.justexample.com/wp/connect-db2-java/
http://www-01.ibm.com/support/docview.wss?uid=swg21419978
I don't understand where to find missing library, on the JDBC library downloaded from the IBM site is missing, have I to copy it from the remote DB2 server or I have to point to the remote location?
thanks in advance best regards.
I found specific package inside IBM embedded software
I suppose you know how to add a jar file in the library of the app. The driver that you are looking for can be found in the IBM folder that generates when you install DB2.
For the driver go to C:/Program Files/IBM/SQLIB/Java there you can find the db2jcc.

The service class "WBSer_RwCnt.Rw_Count" does not comply to one or more requirements of the JAX-RPC 1.1 specification

package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
Class.forName(driver); // load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection();
String tableName = "hospital_status";
System.out.println("tableName=" + tableName);
System.out.println("conn=" + conn);
System.out.println("rowCount=" + countRows(conn, tableName));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// release database resources
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Error --->
The method "getConnection" on the service class "WBSer_RwCnt.Rw_Count" uses a data type, "java.sql.Connection", that is not supported
When i compile it without creating it as webservice it works correctly
but when i make it as web service it gives output as
Output --->
WBSer_RwCnt.Rw_CountSoapBindingStub#121a412b
Please Help !
Next Try
So this is what i have done after what you have said even then it gives following errors
Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
Message:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static int countRows() throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
System.out.println("ram");
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
try {
Class.forName(driver);
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM hospital_status");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
finally {
rs.close();
stmt.close();
conn.close();
}
return rowCount;
}
}
i have the added all jar files including the java mysql connectors
This is not going to be a full answer as I'm not exactly sure about the tools you are using to compile the web service, but anyway, here goes:
Basically, a connection is something that is only valid on a particular machine. If it's a TCP/IP connection, it consists of two pairs: source host and port, and target host and port. If it's a Linux socket, then it is an entry in that particular machine's directory tree.
A database connection is usually built on one of those constructs, so it, too, is particular to a machine.
Therefore, it doesn't make sense to pass a Connection object to the user who calls your method from some remote machine. And since it doesn't make sense, the JAX-RPC standard does not include a serialization for Connection, and that's why it fails.
Your problem is that you have designed your method such that it accepts a connection as a parameter, and uses that connection to access the database. This works OK locally, but is not a good design for a remote service.
Instead, your method should acquire the connection internally. The remote user should access just the countRows method, with the name of the table, and countRows should call getConnection, use the connection, and the close it.
You shouldn't have a main method in a web service. And the getConnection method should be changed from public to private, so that countRows can access it. When it is private, I believe the web service compiler will not complain about it because it doesn't have to create a serialization for it.

Java Eclipse JDBC Oracle: DriverManager.getConnection stuck

while I'm able to connect and query an oracle database using Oracle SQLDeveloper, I'n not able to do the same from a test java application:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#myhost:1521/mysid"; //SID
//String url = "jdbc:oracle:thin:#myhost:1521:myservice"; //service
String usr = "myuser";
String pwd = "mypassword";
System.out.print("Before DriverManager...");
con = DriverManager.getConnection(url, usr, pwd);
if (con == null)
{
System.out.print("Connection is null");
}
else
{
System.out.print("Connection OK");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT count(*) FROM mytable");
while(rs.next()) {
System.out.print(rs.getInt(1));
//System.out.println(rs.getString(2));
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Some system details:
OS: Mac OS X 10.9.4
Java Version: 1.7
Eclipse: Kepler (64bit)
Oracle Client: instantclient_10_2
After some unsuccessful tentatives, I decided to copy exactly the same JDBC driver used by SQLDeveloper (using show package content). I've copied it under my project folder/lib. And then I added the jar to the build path.
When I run the application on my mac it just remain stuck after printing "Before DriverManager..."
If I run the same application on a colleague windows machine it works fine and print the count results.
I'm really out of options, and I'm starting to think there's some issue with my machine java permission. Is it possible? Any idea where I should look for?
Any help is appreciated.
Regards
Stefano

how to install JDBC and how to use it to connect to mysql?

i am trying to install JDBC but i dont know how, when you only have the jar file, i copied it to my java ext folder but it keep giving me an error, can anyone show me how to complete install the driver and use it?
below is the codes that i used
import java.sql.*;
public class Test1
{
public static void main (String[] args)
{
String url = "jdbc:mysql://localhost:3306/sabayafr_sabmah";
String username = "root";
String password = "ma";
Connection connection = null;
try {
System.out.println("Connecting database...");
connection = DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
System.err.println("Cannot connect the database!");
e.printStackTrace();
} finally {
System.out.println("Closing the connection.");
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
}
}
And below is the Response that i get
Cannot connect to database server
Update # 3
C:\Users\AlAsad\Desktop>java -cp .;mysql-connector-java-5.0.8-bin.jar Test1
Connecting database...
Cannot connect the database!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
sabayafr_sabmah
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Test1.main(Test1.java:12)
Closing the connection.
You're trying to connect MySQL with the URL of a jTDS JDBC driver which is designed specifically for Microsoft SQL Server. This ain't ever going to work. Even not when you fix the current problem by placing the JAR file in classpath.
You really need the MySQL JDBC driver. Also see this answer for a short but complete tutorial
On the other hand, if you are using an IDE such as Netbeans or Eclipse you can add the jar file as a resource to the project.
You certainly have JDBC problems, but the exception isn't telling you that. Read it again:
Exception in thread "main" java.lang.NoClassDefFoundError: Test1
Caused by: java.lang.ClassNotFoundException: Test1
It's your Test1.class that it can't find, not the JDBC driver.
You should not be copying anything into the jre/lib/ext directory. That's for library extensions, not JDBC JARs. It wasn't meant as a crutch for people who don't understand how CLASSPATH works.
I'd write it more like the following. Those close methods will come in handy.
When I run it on my machine, adding the MySQL JDBC JAR to my CLASSPATH, I get the following result:
C:\java -classpath .\mysql-connector-java-5.1.6-bin.jar; persistence.utils.DatabaseUtils
product: MySQL
version: 5.1.24-rc-community
major : 5
minor : 1
Here is the source code:
package persistence.utils;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseUtils
{
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/contacts";
public static final String USERNAME = "contacts";
public static final String PASSWORD = "contacts";
public static void main(String[] args)
{
Connection connection = null;
try
{
String driver = ((args.length > 0) ? args[0] : DRIVER);
String url = ((args.length > 1) ? args[1] : URL);
String username = ((args.length > 2) ? args[2] : USERNAME);
String password = ((args.length > 3) ? args[3] : PASSWORD);
connection = getConnection(driver, url, username, password);
DatabaseMetaData metaData = connection.getMetaData();
System.out.println("product: " + metaData.getDatabaseProductName());
System.out.println("version: " + metaData.getDatabaseProductVersion());
System.out.println("major : " + metaData.getDatabaseMajorVersion());
System.out.println("minor : " + metaData.getDatabaseMinorVersion());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
close(connection);
}
}
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Connection connection = null;
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet resultSet)
{
try
{
if (resultSet != null)
{
resultSet.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
'I am trying to install JDBC'
You don't have to install JDBC. It is part of the JDK & JRE.
Try putting your .jar file in the classpath.
The library that contains the Driver (net.sourceforge.jtds.jdbc.Driver) needs to be on the classpath.
Assuming you start your application with
java Test1
then simply do
java -cp .;driver.jar Test1
where 'driver.jar' should be exchanged with the filename (relative or full path) of your database driver lib.
EDIT
A classpath tutorial will exceed the comments section below this question. Please take a cup of coffee and look at this page. It will most likely help you to continue.

Categories