Is there a JDBC 4.1 driver for DB2? - database

Does DB2 (LUW) support JDBC 4.1?
From where can I download this driver if it exist?

The db2 driver for JDBC v3 is called db2jcc.jar
For version 4, the JDBC driver for DB2 is called db2jcc4.jar, and the documentation says: JDBC 4.0 or later functions.
Your question is specific for JDBC 4.1, however the DB2 documentation does not say anything about this JDBC specific release (RowSetProviderClass and auto-close of connection, statement an resultSet)
It does not seem that this jdbc driver is available for this jdbc release.
http://pic.dhe.ibm.com/infocenter/db2luw/v10r5/topic/com.ibm.db2.luw.apdv.java.doc/src/tpc/imjcc_cjvintro.html
List of db2 jdbc drivers: http://www-01.ibm.com/support/docview.wss?uid=swg21363866

As a follow up answer to what #AngocA mentioned above, I developed a simple program to test the DB2 driver to check its compliance level with JDBC.
I found that the first DB2 driver claiming such support is driver 4.13.127.
So any thing after that should also support JDBC 4.1
Here is my simple program you can use to check for the compliance level:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class tester {
// Replace these info with your DB2 info
private final static String hostName = "mydb2.db2.com";
private final static String portNum = "50000";
private final static String userName = "dasusr";
private final static String password = "db2sdin";
private final static String dbName = "mydb";
private final static String fullURL = "jdbc:db2://" + hostName + ":" + portNum
+ "/" + dbName + ":" + "user=" + userName
+ ";password=" + password + ";";
public static void main(String[] args) {
Connection con = null;
try {
con = DriverManager.getConnection(fullURL);
DatabaseMetaData conMD = con.getMetaData();
String driverName = conMD.getDriverName();
String driverVersion = conMD.getDriverVersion();
String jdbcVersion = conMD.getJDBCMajorVersion()
+"."+ conMD.getJDBCMinorVersion();
System.out.println("driverName: " + driverName + "\n"
+"driverVersion: "+ driverVersion + "\n"
+"jdbcVersion: "+ jdbcVersion);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In your .classpath which would look like this in the Navigator tab in eclipse:
add the location of the driver you would like to test like this:
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse
.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<!-- driver_4.13.127 -->
<classpathentry kind="lib" path="driver_4.13.127/db2jcc_license_cisuz.jar"/>
<classpathentry kind="lib" path="driver_4.13.127/db2jcc4.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
You should then get an output similar to this:
driverName: IBM Data Server Driver for JDBC and SQLJ
driverVersion: 4.13.127
jdbcVersion: 4.1

Related

Export Data from Hadoop using sql-spark-connector (Apache)

I am trying to export data from Hadoop to MS SQL using Apache Spark SQL Connector as instructed here sql-spark-connector which fails with exception java.lang.NoSuchMethodError: com.microsoft.sqlserver.jdbc.SQLServerBulkCopy.writeToServer (Lcom/microsoft/sqlserver/jdbc/ISQLServerBulkRecord;)V
According to official documentation Supported Versions
My Development Environment:
Hadoop Version: 2.7.0
Spark Version: 2.4.5
Scala Version: 2.11.12
MS SQL Version: 2016
My Code:
package com.company.test
import org.apache.spark.sql.SparkSession
object TestETL {
def main(args:Array[String]):Unit = {
val spark:SparkSession = SparkSession
.builder()
.getOrCreate()
import spark.implicits._
// create DataFrame
val export_df = Seq(1,2,3).toDF("id")
export_df.show(5)
// Connection String
val server_name = "jdbc:sqlserver://ip_address:port"
val database_name = "database"
val url = server_name + ";" + "databaseName=" + database_name + ";"
export_df.write
.format("com.microsoft.sqlserver.jdbc.spark")
.mode("append")
.option("url", url)
.option("dbtable", "export_test")
.option("user", "username")
.option("password", "password")
.save()
}
}
My SBT
build.sbt
Command line argument I executed
/mapr/abc.company.com/user/dir/spark-2.4.5/bin/spark-submit --class com.company.test.TestETL /mapr/abc.company.com/user/dir/project/TestSparkSqlConnector.jar
JDBC Exception
I de-compiled the mssql-jdbc-8.2.0.jre8.jar to check if it is missing the SQLServerBulkCopy.writeToServer method implementation but that doesn't see to be the case.
Any insights on how I can fix this?
it is a compatability error please to reffer to this link it will explain the error or just choose compatible versions. gitHub link

sbt run won't find external libraries

I have mssql as an external library defined like this in my build.sbt.
libraryDependencies ++= Seq(
...
"com.typesafe.slick" %% "slick" % "3.3.2",
"com.typesafe.slick" %% "slick-hikaricp" % "3.3.2",
"com.microsoft.sqlserver" % "mssql-jdbc" % "7.4.1.jre8"
)
Now, in order to run my main object, I do the following
sbt
run
choose the main object
Now, it seems however, that the driver, i.e. the library cannot be found.
java.lang.RuntimeException: Failed to get driver instance for jdbc
...
Caused by: java.sql.SQLException: No suitable driver
I assume it's simply not included in the class path. Any suggestions on how to fix this?
Edit: I use the following way to acquire a database connection.
object DatabaseUtils {
private val cfg: DatabaseConfig[JdbcProfile] = DatabaseConfig.forConfig("database")
def db: JdbcProfile#Backend#Database = cfg.db
}
With this configuration
database = {
profile = "slick.jdbc.SQLServerProfile$"
db {
host = "<IP>"
port = <port>
databaseName = "<dbname>"
url = "jdbc:sqlserver://"${database.db.host}":"${database.db.port}";databaseName="${database.db.databaseName}
user = "<user>"
password = "<pass>"
}
}
I think you miss the Database Driver. From the documentation:
tsql {
driver = "slick.driver.H2Driver$"
db {
connectionPool = disabled
driver = "org.h2.Driver"
url = "jdbc:h2:mem:tsql1;INIT=runscript from 'src/main/resources/create-schema.sql'"
}
}
I don't use Slick, in our project, the driver for MSSQL is com.microsoft.sqlserver.jdbc.SQLServerDriver

Exception : java.lang.ClassNotFoundException on MS Access Database [duplicate]

I have created an MS Access database and assigned a DSN to it. I want to access it through my Java application.
This is what I am doing:
public class AccessDbConnection {
public static void main(String[] args) {
System.out.println("**ACCESS DB CONNECTION**");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // for MS Access ... MS access driver loading
String conURL = "jdbc:odbc:sampleDNS";
Connection con = DriverManager.getConnection(conURL);
Statement statement = con.createStatement();
String qry = "SELECT * FROM Table1";
ResultSet rs = statement.executeQuery(qry);
while(rs.next()) {
String id = rs.getString("ID") ;
String fname = rs.getString("First_Name");
String lname = rs.getString("Last_Name");
System.out.println(id + fname + lname);
}
} catch (ClassNotFoundException ex) {
System.out.println("Classforname Exception!!");
Logger.getLogger(AccessDbConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
System.out.println("DriverManager Exception!!");
Logger.getLogger(AccessDbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I am getting the exception at the first line of try block. That is class.forname("..");. Why am I having this Exception?
For Java 7 you can simply omit the Class.forName() statement as it is not really required.
For Java 8 you cannot use the JDBC-ODBC Bridge because it has been removed. You will need to use something like UCanAccess instead. For more information, see
Manipulating an Access database from Java without ODBC
in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.
1- hsqldb.jar
2- jackcess 2.0.4.jar
3- commons-lang-2.6.jar
4- commons-logging-1.1.1.jar
5- ucanaccess-2.0.8.jar
add these libraries to your java project and start with following lines.
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();
path could be like E:/Project/JAVA/DBApp
and then your query to be executed. Like
ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));
certain imports to be used. try catch block must be used and some necessary things no to be forgotten.
Remember, no need of bridging drivers like jdbc odbc or any stuff.
Setup:
My OS windows 8 64bit
Eclipse version Standard/SDK Kepler Service Release 2
My JDK is jdk-8u5-windows-i586
My JRE is jre-8u5-windows-i586
This how I overcome my error.
At the very first my Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") also didn't work.
Then I login to this website and downloaded the UCanAccess 2.0.8 zip (as Mr.Gord Thompson said) file and unzip it.
Then you will also able to find these *.jar files in that unzip folder:
ucanaccess-2.0.8.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.4.jar
Then what I did was I copied all these 5 files and paste them in these 2 locations:
C:\Program Files (x86)\eclipse\lib
C:\Program Files (x86)\eclipse\lib\ext
(I did that funny thing becoz I was unable to import these libraries to my project)
Then I reopen the eclipse with my project.then I see all that *.jar files in my project's JRE System Library folder.
Finally my code works.
public static void main(String[] args)
{
try
{
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\Hasith\\Documents\\JavaDatabase1.mdb");
Statement stment = conn.createStatement();
String qry = "SELECT * FROM Table1";
ResultSet rs = stment.executeQuery(qry);
while(rs.next())
{
String id = rs.getString("ID") ;
String fname = rs.getString("Nama");
System.out.println(id + fname);
}
}
catch(Exception err)
{
System.out.println(err);
}
//System.out.println("Hasith Sithila");
}
add these dependecies to your .pom file:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.healthmarketscience.jackcess</groupId>
<artifactId>jackcess-encrypt</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
and add to your code to call a driver:
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://{file_location}/{accessdb_file_name.mdb};memory=false");
Make sure you have closed your MSAccess file before running the java program.

Error in Jenkins using SQL Server Driver

I'm trying to run a Groovy script to connect to Microsoft SQL Server within Jenkins and insert new data . I want to use the SQL Server driver and I placed the driver in Jenkins\war\WEB-INF\lib. I get an error when I Tried to run the following code in the build step - Execute Groovy Script:
import groovy.sql.Sql
import com.microsoft.sqlserver.jdbc.SQLServerDriver
class Connection {
def sqlConnection
def route = "xxxx"
def user = "xxxx"
def password = "xxxxx"
def driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
Connection(db){
this.route+=db.toString()
this.sqlConnection = Sql.newInstance( route, user, password, driver )
}
static main(args) {
Connection con = new Connection("nameDataBase")
}
}
The error is:
1 error org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
E:\Jenkins\workspace\pruebaDB\hudson1035758401251924782.groovy: 2:
unable to resolve class com.microsoft.sqlserver.jdbc.SQLServerDriver # line 2, column 1.
import com.microsoft.sqlserver.jdbc.SQLServerDriver`
The most evident case of such exception is that necessary class not yet in classpath during script execution.
During a which build step script is executed?
If my assumptions are right and you can't shift script execution time to the other build step (when all necessary classes/libs will be in the cp) try to use class loader.
Here is a few links which should help you with this:
class lodding fun
class loading in groovy

Compact Access 2007 Database on 64bit windows 2008 Server

I am facing problem while using JRO in winform application to compact access database on windows server 2008 R2 (64bit) server. I followed below steps:
Configuration of Development PC:
OS : Windows XP Professional Ver: 2002 (SP3) 32Bit
MSOffice 2003 Installed: Yes
Visual Studio: 2010 Premium
.Net framework: 4.0.30319
Two winform App with below code are created:
Application 1: For compacting Access 2007 DB
Target Platform is set to x86 and Added reference of Microsoft Jet and Replication Objects 2.6 Library
Config file:
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/></startup>
<appSettings>
<add key="SourceDB" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Test\Test2007.accdb;Jet OLEDB:Engine Type=5"/>
<add key="DestDB" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Test\Test2007BK.accdb;Jet OLEDB:Engine Type=5"/>
<add key="AppDB" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Test\Test2007.accdb;" />
</appSettings>
</configuration>
Code:
string SrcDBName = ConfigurationManager.AppSettings["SourceDB"];
string DestDBName = ConfigurationManager.AppSettings["DestDB"];
int ReturnCode = 0;
JRO.JetEngine objJRO = null;
try
{
MessageBox.Show("Start Compact");
objJRO = new JRO.JetEngine();
objJRO.CompactDatabase(SrcDBName, DestDBName);
MessageBox.Show("End Compact");
}
catch (Exception ex)
{
MessageBox.Show("Error in Compact");
ReturnCode = -1;
StackTrace STrace = new StackTrace(ex, true);
StackFrame StkFrame = STrace.GetFrame(STrace.FrameCount - 1);
string Disp_Msg = "Message:\t" + ex.Message + Environment.NewLine;
Disp_Msg += "Error Date:\t" + DateTime.Now.ToString("dddd, MMM d yyyy HH:mm:ss");
//MessageBox.Show(Disp_Msg, "Compact Utility", MessageBoxButtons.OK, MessageBoxIcon.Error);
File.AppendAllText(Path.GetDirectoryName(Application.ExecutablePath) + #"\CompactErr.txt", Disp_Msg + Environment.NewLine + "Stack Trace:\t" + ex.StackTrace + Environment.NewLine + Environment.NewLine);
}
finally
{
Marshal.ReleaseComObject(objJRO);
objJRO = null;
}
Application 2: For Testing Connection with Access 2007
private void Form1_Load(object sender, EventArgs e)
{
try
{
//Connection Test
MessageBox.Show("Start DBConn");
TestConn();
MessageBox.Show("End DBConn");
}
catch (Exception ex)
{
MessageBox.Show("Error in Conn Opening");
string Disp_Msg = "Message:\t" + ex.Message + Environment.NewLine;
Disp_Msg += "Error Date:\t" + DateTime.Now.ToString("dddd, MMM d yyyy HH:mm:ss");
File.AppendAllText(Path.GetDirectoryName(Application.ExecutablePath) + #"\CompactErr.txt", Disp_Msg + Environment.NewLine + "Stack Trace:\t" + ex.StackTrace + Environment.NewLine + Environment.NewLine);
}
}
public void TestConn()
{
string strConnectionString = ConfigurationManager.AppSettings["AppDB"];
DbConnection objConnection;
DbProviderFactory objFactory = OleDbFactory.Instance;
objConnection = objFactory.CreateConnection();
objConnection.ConnectionString = strConnectionString;
objConnection.Open();
objConnection.Close();
}
Now above 2 exe are deployed on Win2008 Server:
Server Details:
Windows Server 2008 R2 (SP1) - 64bit
NO MSOffice
NO Visual Studio
Installed: Microsoft Office Access Database Engine 2010
Case 1: when Access DB Engine 2010 (64bit) is installed:
Link: http://www.microsoft.com/download/en/details.aspx?id=13255
Connection to Access 2007 (Test2007.accdb) is CORRECTLY DONE
Compact of DB using JRO NOT WORKED
Error Message while executing Step 2:
Message:Class not registered
Stack Trace:at JRO.IJetEngine.CompactDatabase(String SourceConnection, String Destconnection)
at CompactUtility.Program.Main(String[] args)
Case 2: when Access DB Engine 2007 is installed:
Link: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=23734
Connection to Access 2007 (Test2007.accdb) is NOT DONE
Compact of DB using JRO CORRECTLY WORKED
Error Message while executing Step 1:
Message: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Any Suggestion/help will be highly appreciated to solve both working on windows server 2008 (64bit) server.
Also refereed below links but not helpful:
Microsoft.ACE.OLEDB.12.0 provider is not registered
Thanks,
Shah
I know, it's an old question but still, This link did help me with the second issue.
If i remember correctly, the problem stems from a 64bit issue with the engine.
Adding the Component into Visual Studio should fix this behaviour.

Resources