JDBC Driver Loading error - java

below is my simple program of JDBC Oracle Connectivity. Please see and tell me why could I possibly get the error of driver not loading. I have put odbc14.jar in libraries.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package databaseconnect;
/**
*
* #author compaq
*/
import java.sql.*;
public class Education1 {
public static void main(String[] args) {
try{
Class.forName("oracle:jdbc:driver:OracleDriver");
}catch( Exception e ) {
System.out.println("Failed to load Oracle driver.");
}
try{
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","system");
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into Education(name,rollno) VALUES ('alankrit',1000)");
System.out.println("Data inserted");
con.close();
} catch(Exception e){
// System.out.println(e);
}
}
}

You need to pass the class name as below, replace : with .
Class.forName("oracle.jdbc.driver.OracleDriver");
Driver Implementation class with complete packages name in String format.
So that reflection api can load this class during run time

instead of
Class.forName("oracle:jdbc:driver:OracleDriver");
use
Class.forName("oracle.jdbc.OracleDriver");
and make sure you have odbc14.jar file in your classpath.

Related

Problems connecting to sqlite database in java

I am following a tutorial on connecting my SQLite database to a Java application.
When I run the program I get the following error in the console of NetBeans:
run:
Error connecting to the databasejava.sql.SQLException: No suitable
driver found for jdbc:C:\Users\lawman\Documents\Java Working
Directory\LoginSql\src\project123.sqlite
BUILD SUCCESSFUL (total time: 0 seconds)
Here is my directory:
I have code to connect to the database in class tobecalledbymain.
I have main in mainclass which creates an instance of tobecalledbymain.
In my library file, I have sqlite-jdbcs.jar imported.
Here is the code for tobecalledinmain:
import java.sql.*;
public class tobecalledinmain {
public tobecalledinmain(){
Connection con = null;
Statement st=null;
ResultSet rs=null;
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:C:\\Users\\lawman\\Documents\\"
+ "Java Working Directory\\LoginSql\\"
+ "src\\project123.sqlite");
st=con.createStatement();
//select all records from the table employee
//table has three firlds: employeeid,name and surname
rs=st.executeQuery("SELECT * FROM Employee;");
while (rs.next())
{
int id = rs.getInt("Employeeid");
String name = rs.getString("Name");
System.out.println("id = " + id);
System.out.println("name= " + name);
System.out.println();
}
rs.close();
st.close();
con.close();
}catch(Exception e)
{
System.out.println("Error connecting to the database" + e);
}
}
}
Here is the mainclass code:
public class mainClass {
public static void main(String[] args){
new tobecalledinmain();
}
}
;;
I am not sure why we need to semi-colons!
Anyway, when the tutorial concludes he gets a result from the console. I get the said error message.
What are the drivers in the error message referring to and how do I get them?
Your jdbc connection string does not specify sqlite. Try this, and use forward slashes.
Connection con = DriverManager.getConnection("jdbc:sqlite:C:/PATH/TO/database.db");
This was the WRONG answer, pls disregard.
You need to add the .jar for the SQLite database driver to your classpath when you run your code. See https://bitbucket.org/xerial/sqlite-jdbc
You can see how to do that in Netbeans here: How to add a JAR in NetBeans

Showing error-no suitable driver found for jdbc:oracle:thin:#localhost:1521:orcl

I am using jdk1.8 and I am trying to execute a jdbc program manually on oracle 8i. My code is compiling without any error but at the run time its showing error-no suitable driver found for jdbc:oracle:thin:#localhost:1521:orcl. I have already set the class path for jar file. I am using ojdbc7.jar file.
My code is:
import java.sql.*;
class Database
{
public static void main(String arg[])
{
try
{
String url="jdbc:orcl:thin:#localhost:1521:orcl";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(url,"scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from aj1");
while(rs.next())
{
System.out.println("\n"+rs.getInt(1)+" "+rs.getString(2));
}
}
catch(Exception e){e.printStackTrace();}
}
}
Kindly give the solution for this:
You url String must be
String url="jdbc:oracle:thin:#localhost:1521:orcl";
instead of
String url="jdbc:orcl:thin:#localhost:1521:orcl";
and try.

Connect Java to Access DB on network drive

I'm creating a desktop Java application that will connect to an access database, using ucanaccess as a driver.
The entire thing will be located on a shared network drive.
I use an absolute file path to connect to my database. I expect this database to outlast my tenure at the office. What happens when another user moves the database, or changes the name of the folder etc... I'm the only Java geek in the office, so this needs to be somewhat automated or easily doable for someone who is... well let's just say not computer literate.
I'm looking for ideas on how to get around this. I thought of opening a file dialog and having the user select the location of the file, but this seems like too much work for the kind of people I work with. It should just open...
Any help is much appreciated. Code sample below.
package databaseTest;
import java.sql.Connection;
import java.sql.DriverManager;
public class test {
public test() {
try {
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
Class.forName(driver);
Connection cnct = DriverManager.getConnection("jdbc:ucanaccess://c:\\users\\Christopher\\Desktop\\JavaProject\\Database11.accdb", "", "");
System.out.println("Connected");
} catch(Exception ex) {System.out.println(ex.getMessage());}
}
public static void main(String[] args) {
System.out.println("connecting...");
new test();
}
}
Suggestion:
I would suggest you to store the database related parameters/configurations
Path to database
Name of network shared directory
Database Name
etc. in a properties file. You can then load the properties file using getResourceAsStream. You only need to ensure two things —
The properties file is in a directory which is in the project build path.
If any of the parameter(s) are changed(files moved/renamed), the corresponding value(s) in the properties file are changed also.
Here's one concrete example(tested on Ubuntu Linux).
Let's say we have a:
MS Access database named Foo.mdb stored under a shared directory /path/to/sharedDirectory
Shared directory named shared_dir
MyDatabaseProperties.properties:
pathToDB = /path/to/sharedDirectory
sharedFolderName = shared_dir
databaseName = Foo.mdb
Table Definition:
Example:
package com.stackoverflow.questions.Q32641670;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
/**
* Initializes a connection to an MS-Access DB using JDBC/UCanAccess API, inserts a record and closes the connection.
* <p>
* ADDITIONAL JARS REQUIRED:
* ------------------------
* commons-lang-2.6.jar
* commons-logging-1.1.1.jar
* hsqldb.jar
* jackcess-2.1.0.jar
* ucanaccess-2.0.9.5.jar
*
* #see #link {https://stackoverflow.com/questions/32641670/connect-java-to-access-db-on-network-drive}
* #since 18/9/15.
*/
/**
* #author Sandeep Chatterjee
* #version 1.0
*/
public class ConnectRemoteDB {
/**
* #param args The command line arguments
*/
public static void main(String[] args) throws IOException {
initializeConnection();
}
/**
* Initializes remote database connection and inserts a record and closes the connection.
*/
private static void initializeConnection() throws IOException {
System.out.println("Attempting Database Connection...");
Connection connection = null;
PreparedStatement preparedStatement;
try {
final Properties PROPERTIES = new Properties();
InputStream inputStream = ConnectRemoteDB.class.getResourceAsStream("/MyDatabaseProperties.properties");
PROPERTIES.load(inputStream);
String pathToDB = PROPERTIES.getProperty("pathToDB");
String sharedFolderName = PROPERTIES.getProperty("sharedFolderName");
String databaseName = PROPERTIES.getProperty("databaseName");
String connectionString = "jdbc:ucanaccess:///" + pathToDB + "/" + sharedFolderName + "/" + databaseName;
connection = DriverManager.getConnection(connectionString, PROPERTIES);
System.out.println("CONNECTION ESTABLISHED....");
String insertTableSQL = "INSERT INTO Table1" + "(Name) VALUES"
+ "(?)";
preparedStatement = connection.prepareStatement(insertTableSQL);
preparedStatement.setString(1, "A");
preparedStatement.executeUpdate();
System.out.println("RECORD INSERTED...");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
System.out.println("CONNECTION CLOSED...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Again:
If you move the database to a different shared directory, set the value of pathToDB accordingly.
If you rename the shared directory, set the value of sharedFolderName accordingly.
If you rename the database, set the value of databaseName accordingly.
The simplest solution is to put the accdb file in a location relative to the java class and not use an absolute path.
For example if the java class (or jar you have packaged your program into as it may be) resides at c:\share\foo.class (or c:\share\foo.jar) then put the acdb file in the same directory structure e.g. c:\share\database\Database11.accdb.
You can then use a relative path in the connection string:
Connection cnct = DriverManager.getConnection("jdbc:ucanaccess:database/Database11.accdb", "", "")

What is the purpose of calling Class.forName() without saving a reference to the object it returns?

In the example below showing how to use Java's SQL library, Class.forName() is called without a variable to save a reference to the object. What is the purpose of doing this if you cannot manipulate it later? I've seen that line written in various examples of the SQL library.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
It makes the class initializer run - which in the case of JDBC drivers used to be the way that the driver would register itself with DriverManager. In modern Java, JDBC drivers are usually found using the service provider API.
From the docs:
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

Error getting connection to database from pool using in servlet

well I have a pretty awkward situation. I have a working database managers class, which works when I run it on the desktop version of it (Swing GUI), however, when I run the same class on the servlet, I get a strange error, that it can't get the connection. I am using database pooling for optimisation.
So the error looks as follows:
Error in Database Connection: Error getting connection to database - java.sql.SQLException: No suitable driver found for jdbc:sqlserver://isd.ktu.lt:1433;DatabaseName=LN2012_bakDB2
And the class with the methods involved looks like this:
package Core;
import DataTypes.Parameters;
import Interfaces.OutputInterface;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
*
* #author arturas
*/
public class DatabaseConnection {
String specificError = "Error in Database Connection: ";
OutputInterface gui = null;
boolean allowOutput = true;
GenericObjectPool connectionPool;
ConnectionFactory connectionFactory;
PoolableConnectionFactory poolableConnectionFactory;
PoolingDriver driver;
Connection con = null;
public DatabaseConnection(Parameters params) {
// parameters and the output
this.gui = params.getGui();
// activate database pool
connectionPool = new GenericObjectPool(null);
connectionFactory = new DriverManagerConnectionFactory(params.getDbAdr(), params.getDbUser(), params.getDbPass());
poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
driver = new PoolingDriver();
driver.registerPool("GenTreeDatabase", connectionPool);
}
public void openConn() {
if (allowOutput) gui.print("Getting connection to database");
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:GenTreeDatabase");
if (con != null) {
if (allowOutput) gui.print("Connection to database was successful");
}
} catch (SQLException ex) {
gui.err(specificError + "Error getting connection to database - " + ex);
}
}
public void closeConn() {
try {
con.close();
if (allowOutput) {
gui.print("Connection to database closed successfully");
}
} catch (SQLException ex) {
gui.err(specificError + ex);
}
}
The error appears when the try in method openConn is called.
Can anybody help me with this?
You are getting this error because there is no drivers in your classpath. Probably in your desktop application there were. You need to put driver's .jar file into your servlet container's global classpath or in your application classpath and it should work.
I prefer adding driver's jar into server global classpath, because there can be more than one application which will use the same .jar file to load drivers.
make sure of this
1) you should make sure that .jar library is compatabile with RDMS you are using
2) that you included the .jar for connection in your netbeans in
projectproperties-->libraries
3)copy the .jar into C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.26\lib
and this is important
if you dont have the driver in location you get not found error but
you get no suitable so i think the version must be incompatible so what version of sql server are you using...

Categories