Connecting JDBC with Firebirdsql - java

I had a problem in connecting with the firebirdsql.
here is my code.
try {
Class.forName("org.firebirdsql.jdbc.FBDriver");
Connection con= DriverManager.getConnection("jdbc:firebirdsql:localhost/3050:C:\\EMPLOYEE.FDB","sysdba","masterkey");
Statement stm= con.createStatement();
ResultSet res= stm.executeQuery("SELECT * FROM Emp");
while (res.next()) {
System.out.println("EMPLOYEE NAME:"
+ res.getString("NAME"));
}
} catch (Exception e) {
System.out.println(e);
}
Getting an ERROR like.
java.lang.ClassNotFoundException: org.firebirdsql.jdbc.FBDriver

The java.lang.ClassNotFoundException: org.firebirdsql.jdbc.FBDriver indicates that you do not have Jaybird (the Firebird JDBC driver) on your class path, as Java failed to load the driver class.
You can download Jaybird from https://www.firebirdsql.org/en/jdbc-driver/
You need to make sure that jaybird-full-2.2.12.jar (or jaybird-2.2.12.jar and lib/connector-api-1.5.jar) are on the class path when you run the application.
This means that you either need to include it in the manifest, or you need to explicitly specify it when running Java:
java -cp .;jaybird-full-2.2.12.jar MyClass
Alternatively, if you use Maven, you can include the dependency using:
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird-jdk18</artifactId>
<version>2.2.12</version>
</dependency>
See also the Jaybird JDBC Driver Java Programmer's Manual, specifically chapter 2.
The use of Class.forName("org.firebirdsql.jdbc.FBDriver"); is not necessary with Jaybird 2.2 and higher.

Related

groovy: Caught: java.sql.SQLException: No suitable driver found even if use #GrabConfig(systemClassLoader=true)

I have this test code to connect to a SQL Server:
#GrabConfig(systemClassLoader=true)
#Grab(group='com.microsoft.sqlserver', module='mssql-jdbc', version='9.2.1.jre8')
import groovy.sql.Sql
def server = '10.6.6.1'
def port = '1433'
def user = 'sa'
def password = 'somepassword'
def url = "jdbc:sqlserver://${server}:${port};databaseName=master;"
Sql.withInstance(url, user, password) { sql ->
def serverName = sql.firstRow('SELECT ##SERVERNAME')
assert serverName[0]
}
if I run it I get:
Caught: java.sql.SQLException: No suitable driver found for jdbc:sqlserver://10.6.6.1:1433;databaseName=master;
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://10.6.6.1:1433;databaseName=master;
at test.run(test.groovy:12)
the jar for the driver is downloaded by Grape for sure because inside subdirectories in .groovy/ directory in my home dir I can find it.
But no way I am not able to connect to the server.
I am using groovy 3.0.9 but I tried with older versions and it's the same.
Edit:
If I add to the code before connecting:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
It works, but it's very strange, I was sure that this is not necessary anymore.
If someone can explain.
it still required to register sql driver in java.sql.DriverManager
every jdbc driver contains approximately the following code usually in XyzDriver class:
static {
try {
java.sql.DriverManager.registerDriver( new XyzDriver() )
} catch (SQLException e) {
...
}
}
the same for microsoft sql driver: https://github.com/microsoft/mssql-jdbc/blob/09d35bfc2338f1fc7c41a958d1e627fa0d6a2b65/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDriver.java#L732
that's why you have to call a code like Class.forName("XyzDriver") to make driver self-register in DriverManager
UPD: JDBC 4.0 / java8+
from javadoc: https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html
JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver ...
When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.
mssql-jdbc-9.2.1.jre8.jar is 4.0 compatible. it contains com.microsoft.sqlserver.jdbc.SQLServerDriver in META-INF/services/java.sql.Driver file
however let's check DriverManager code and how it looks up for drivers:
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/sql/DriverManager.java#l100
static {
loadInitialDrivers();
println("JDBC DriverManager initialized");
}
DriverManager tries to find drivers at the moment it's loaded. so, jdbc driver must be present in classpath at app startup to be auto-registered.
and it's not the case with #Grab in code.
as workaround after grab you could do this to call self-register for all drivers:
ServiceLoader.load(java.sql.Driver.class).iterator().findAll()

JavaFx SQLite driver is not suitable

I am trying to connect to a SQLite database on my local device (Ubuntu).
my setup is VS Code with Maven
The error
java.sql.SQLException: No suitable driver found for jdbc:sqlite:/home/idir/embag/chek/Data/Checks.sql
Database.java, connect method
public void Connect() {
String AbsolutePath = new File("").getAbsolutePath();
path = "jdbc:sqlite:"+ AbsolutePath + DATABASE_PATH + DATABASE_NAME ;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(path);
if (conn != null){
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " + meta.getDriverName());
System.out.println("A new database has been created.");
}
}
catch(Exception e){
System.out.println(e.toString());
}
}
Maven pom.xml
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
Module-info.java
requires java.sql;
requires mysql.connector.java;
What I tried
+3 hours of search with no hope
I fixed the problem by removing the MySQL dependency as pointed out by the previous responses .
Added to the Module-info.java:
requires org.xerial.sqlitejdbc;
Also added this to pom.xml:
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/services/java.sql.Driver</resource>
</transformer>
Don’t mix database engines
You are asking your MySQL driver to make a connection using a string meant for SQLite.
MySQL and SQLite are two entirely separate different database engines. So your code makes no sense.
By the way…
In modern Java, there is no need to call Class.forName. JDBC drivers are now automatically loaded via the Java SPI facility.
Generally best to separate your code for configuring the database connection info from the code that accesses the database. Have the first produce a DataSource object that is passed into the second.

Cant connect Java to MariaDB

I cant connect java to MariaDB .I saw all similar questions answers but none has solved my problem. Here is my 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 mariadbtest;
import java.sql.*;
/**
*
* #author AAAA
*/
public class MariaDBTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args){
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
String url = "jdbc:MariaDB://localhost:3306/customer"; // url to access the DB
String user = "root";
String pwd="password";
Connection connection = DriverManager.getConnection(url,user,pwd);
System.out.println("Connected to MariaDB");
}
catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
catch (Exception ex) {
System.out.println("Exception: "+ ex.toString());
}
// TODO code application logic here
}
}
Note the following :
I am using the connector mysql-connector-java-8.0.22.
I have the latest java version.
MariaDB version is 10.3.27.
I have copied the connector to the lib directory in java folder in program files .
I have added the connector JAR file to my project through properties --> Libraries --> Add JAR/Folder.
MariaDB has the service name MariaDB.
The database name is customer.
error :
SQL Exception: java.sql.SQLException: No suitable driver found for jdbc:MariaDB://localhost:3306/customer
BUILD SUCCESSFUL (total time: 3 seconds)
I think that the problem is that you are using a MySQL Connector/J JDBC driver with a URL that it doesn't recognize. This URL
jdbc:MariaDB://localhost:3306/customer
says to look for a driver from a "MariaDB" provider. But apparently the MySQL drivers don't advertise themselves (via SPI) as being MariaDB drivers.
Solution
First of you should get rid of this:
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
It is not needed, and you are hard-wiring a driver classname into your code. Get rid of the associated exception handler clauses too. (This is all Voodoo Programming stuff. It might have been needed 20 years ago ... but not anymore.)
You can fix the driver resolution problem in two ways:
Change the URL to this:
jdbc:mysql://localhost:3306/customer
According to the MariaDB documentation, the MySQL Connector/J driver is compatible with MariaDB. But use of "MariaDB" in the JDBC url not mentioned in the MySQL Connector/J documentation.
Switch to the MariaDB Connector/J driver. According to the documentation, this should support
jdbc:mariadb://localhost:3306/customer
or
jdbc:mysql://localhost:3306/customer
It is not clear from the docs whether the case of the "protocol" part matters. However, syntax specification in the MariaDB doc uses "mariadb" not "MariaDB", so I would recommend lower-case for stylistic consistency.

Unable to get string of query using driverspy

I am working on a project where I need to log query in Log files and add those queries to my assert statement as well
I have build prepared statements using below driver
net.sf.log4jdbc.sql.jdbcapi.DriverSpy
And url
jdbc:log4jdbc:sybase:Tds ........
Dependencies I am using is as below:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
PrepareStatement Example:
public void getTest(MyBean bean) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DatabaseUtil.getDatabaseConnection();
ps = conn.prepareStatement(objTestQueryUtil.getQuery("GET_Test"));
ps.setString(1, bean.getTypeOfTest());
ps.setString(2, bean.getTest());
ps.setString(3, bean.getTestState());
ps.setString(4, bean.getTestStep());
rs = ps.executeQuery();
while(rs.next()) {
bean.setTest(rs.getInt("Test"));
}
}catch (SQLException e) {
AutomationLog.error(e.getMessage(),e);
}finally {
DatabaseUtil.close(conn,ps,rs);
}
}
In my assert class, the sql should see in my assert code like:
Assert.assertTrue("Got Test "+query, true);
Can you please tell me if there any way around by which I can get query in variables in java also, currently query directly logs into the log file and I am not able to find anyway by which I can get them in my script, i.e store on any variable etc
Another dependencies or solution are also welcome if current dependencies do not have such provisions for pre-prepared-statements
This is not the optimal solution but it can solve your problem:
Open your jtds jar file (or download the jtds source files and import them in your IDE), find and decompile the class net.sf.log4jdbc.StatementSpy.class,
add a static String variable in that class, let's call it myLastExecutedSQL
edit the reportSQL() method, assign the sql method parameter to your static variable
compile the new class (or regenerate the jar) and use it in your project
in your test class you will be able to access the last executed query with StatementSpy.myLastExecutedSQL
As you're using maven you will have to replace the jar on the maven home folder
The drawback of this is that you cannot use it in a multi-threaded environment, but it will do the trick.
I hope it's clear enough

Ms Access Connect to Java [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.

Categories