JDBC for SQLite in Netbeans: No suitable driver found - java

I need to load data from an SQLite file into a java program which I develop in Netbeans.
The file is to be loaded via a swing menu item. I'm using sqlitejdbc as driver.
Here are the code blocks I assume to be important:
// header stuff
package aufgabe_9;
import java.sql.*;
//...
// menu item opening the file
private void mitemOpenFileActionPerformed(java.awt.event.ActionEvent evt)
{
/**
* Handles the dialogue for selecting and loading file.
*/
JFileChooser fileChoose = new JFileChooser();
fileChoose.showOpenDialog(this); //'this' calls the current object
//Load the sql file
try {
String filePath = fileChoose.getSelectedFile().toString();
Connection conn = DriverManager.getConnection("jdbc:sqlite:" +
filePath);
//Close the connection
if (conn != null)
conn.close();
}
catch (SQLException e){System.err.println("Database problem: " + e);}
}
}
//...
When running the program and loading a file via the menu, I get the following error:
java.sql.SQLException: No suitable driver found for jdbc:sqlite:/home/levent
/temp/A9AProbeflaeche.db
After reading the respective stackexchange posts, I understand that this
problem can be caused by (1) a malformed file URL or (2) the driver not being
loaded. Here's some further information:
I added the sqlitejdbc-3.7.2.jar to the library classpath via Tools --> Libraries as well as to the project libraries via Window --> Projects.
I also checked the Classpath by using this function. It contains the path to the jdbc jar-file just as expected.
I can connect to the database via the Services menu without any problems, so I can assume the URL to be correct, as well as sqlite running on my system.
Some OS information: I'm running Netbeans 8.0 on 64 bit ARCH Linux 3.12.9-2.
Can anybody tell me what I'm missing here? Any help appreciated!
Problem solved
Here is the code that works for me:
//...
private void mitemOpenFileActionPerformed(java.awt.event.ActionEvent evt)
{
/**
* Handles the dialogue for selecting and loading file.
*/
JFileChooser fileChoose = new JFileChooser();
fileChoose.showOpenDialog(this);
//Load the sql file
try {
//Get file path
String filePath = fileChoose.getSelectedFile().toString();
//Open connection
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + filePath);
//Do stuff...
//Close the connection
conn.close();
}
//"Multicatch":
catch (SQLException | ClassNotFoundException e) {
System.err.println("Database problem: " + e);
}
//...

You probably need to load the driver class so that it registers itself to the DriverManager using the following code:
Class.forName("org.sqlite.JDBC");
Note: this only needs to be called once in your application.
This was a standard procedure before the Java included the ServiceLoader API, now the DriverManager uses that API to register the drivers it finds in the classpath, but the drivers need to declare a file named java.sql.Driver containing the name of the driver class in the directory META-INF\services of their jar.

Related

Cannot connect to access database from jar file [duplicate]

This question already has an answer here:
Manipulating an Access database from Java without ODBC
(1 answer)
Closed 6 years ago.
I cannot connect to my access database using jdbc:ucanaccess driver.
Here the code:
public void open_conn()
{
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String url = "jdbc:ucanaccess://C:\\AnalysisLab\\dbanal.accdb";
conn = DriverManager.getConnection(url, "username", "password");
stmt = conn.createStatement();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Error: "+e.getLocalizedMessage()); e.printStackTrace();
}
}
The error reported : "Error: net.ucanaccess.jdbc.UcanaccessDriver"
I tried including org-netbeans-modules-db-mysql.jar file in the jar directory, but it doesn't work.
This documentation says that your URL should be in the following format:
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://",user, password);
// for example:
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://c:/pippo.mdb");
So your URL is going to change to:
String url = "jdbc:ucanaccess://C:\\AnalysisLab\\dbanal.accdb";
And add the following jar files to your CLASSPATH as all of these are needed by the actual JDBC driver itself:
ucanaccess-3.0.3.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.3.jar
As per your question, I assume that you are on Netbeans and hence you need to all these 5 jars there in the following manner:
Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.
A very detailed explanation of a similar question can be found here.

Java-How Do I Rerefrence Sqlite Database in the Same Folder With My Project Files?

am working on a certain java Management System where am using sqlite as my primary database. Am using netbeans gui builder to work on my project. I have googled and stack overflowed how to reference sqlite database in the same dir with my project files without including full path like c://filepath but nothing promising yet. I don't want to include the full path to my database, I want to use sqlite file from the project files so that everything will work smoothly even after distributing my project...
My Connection Class currently Looks like this;
import java.sql.Connection;
import java.sql.DriverManager;
public class Connect {
private static Connection con = null;
public static Connection connecting(){
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:programming.sqlite");
JOptionPane.showMessageDialog(null, "Working", null, JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
}
return con;
}
}
However that's seems not to work.. Remember Connection class and database are saved in the same dir...
Please note am avoiding absolute path like c://users/programming.sqlite
Anything to help please???
I think it must work as you shown, but, you can load programming.sqlite as a java.io.File and then put absolute path into jdbc url connection. I mean this:
File temp = new File("programming.sqlite");
String connection = "jdbc:sqlite:" + temp.getAbsolutePath().replace("\\","\\\\");
con = DriverManager.getConnection(connection);
...
If this code doesn't work for you, then your problem must be with programming.sqlite location, because in this case it is not on the same home dir of your java programm.

SQLite Exception Path does not exist

I am trying to connect an already existing SQLite database to my java project, as a temporary solution for testing a simple log-in dialog. Here is my connector class:
import java.sql.*;
import javax.swing.*;
public class SQLite_login_connector {
//Initializes global connection variable (unused until now!)
Connection conn_log = null;
public static Connection logindb_connection(){
//Simple try catch block that prints error trace log in a JOptionPane if runtime error occurs.
try{
Class.forName("org.sqlite.JDBC");
Connection conn_log = DriverManager.getConnection("jdbc:sqlite:/SQLite/ISRSMS_Login.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!");
return conn_log;
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
My SQLite database is located in a folder within my project folder:
When I try running my connector class, it throws the following exception:
For me it looks as if it assumes that the folder which contains my database is located on my F: drive, as opposed to my root project in my local repository. I have tried putting the database into my src folder, as well as into a new resource folder all-together. Every time it throws the same exception. Why does it do that?
As you have metntioned / in yor connection string it is pointing to the root directory of your drive
Remove the / in your connection string Do as follows
DriverManager.getConnection("jdbc:sqlite:SQLite/ISRSMS_Login.sqlite")
For your convenience please follow the naming convention of java language
http://www.oracle.com/technetwork/java/codeconventions-135099.html
Why is your URL .sqllite? I would expect .db - like here
jdbc:sqlite:C:/mydir/mydb.db

Connecting to a mySQL database using Java

So I just started learning about databases this week and one of the things I need to be able to do is connect to my mySQL database that I created using Java. I have done some research and I have tried to find the correct way of doing this I just can't seem to figure out how. Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Menu
{
public void menu()
{
Connection conn;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "gym";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
}
catch (Exception e)
{
System.out.println("NO CONNECTION =(");
System.out.println(e.getMessage());
}
}
}
Now the problem is, is that every time I run this code, the "No Connection =( " appears and then it says the error is: "com.mysql.jdbc.Driver". Can somebody please help me and say what I am doing wrong? Thank you. Much appreciated.
Your error means that your library path doesn't contain the jar that contains the com.mysql.jdbc.Driver class.
You don't have to change anything in your code. If you are running it via Eclipse, you should add mysql-connector-java-x.x.x-bin.jar to your build path (where x.x.x is the version of the jar).
All JDBC connection classes need their respective drivers which are normally supplied as jar files from the database vendor, add the relevant database driver to your classpath.
The .jar file will be available from the vendors site, in this case : http://www.mysql.com/products/connector/ and then to add this to the classpath of your project in the ide of your choice. Here is a guide for eclipse : http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)
Try and run again once you have this.

Java connection to MS Access Database

Just wondering if anyone cane help me, I'm trying to connect to an MS Access Database. I have done it on other projects and used exactly the same code. Can anyone see if I have done anything wrong?
try {
System.out.println("Attempting Database Connection");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver(*.mdb)};DBQ=MotivationDatabase.mdb;";
connection = DriverManager.getConnection(sourceURL, "", "");
stmt = connection.createStatement();
System.out.println("Connection made");
} catch (Exception e) {
System.out.println("Database connection attempt failed");
System.out.println(e);
}
I keep getting the error:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Could not find file '(unknown)'.
But my database is in the same folder as my project like I've done before s I'm not sure why i am getting this error. Help?
Control Panel -> Administrative Tools -> ODBC Data Sources -> Add -> Microsoft Access Driver(*mdb,*accdb)
Specify the correct path to MotivationDatabase.mdb corresponding to Data Source name and save the settings.
Refer here.
Code:
public class Main {
#SuppressWarnings("unused")
public static void main(String[] args) {
try {
System.out.println("Attempting Database Connection");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="
+ "D:\\MotivationDatabase.mdb";
Connection connection = DriverManager.getConnection(sourceURL);
System.out.println("Connection made");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
P.S: Please learn to work with JDBC as JDBC-ODBC Bridge will be removed in JDK8.See here.
EDIT:
You can also use JDBC along with UCanAccess API to connect to an MSAccess database. You would need the following jars in your project build path.
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.0.jar
ucanaccess-2.0.9.5.jar
Code:
connection = DriverManager
.getConnection("jdbc:ucanaccess:////REMOTE-IP-ADDRESS/shared-folder/TestDB.mdb");
System.out.println("CONNECTION ESTABLISHED....");
Works fine with JDK8. You can download the entire source code from here.
Sun JDBC ODBC will notte work with MS access when java 8 will ne release: I suggest you to use apache poi project. It s simple and works great.
Yeah it's correct the right project is jakcess:
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Row;
import com.healthmarketscience.jackcess.Table;
try{Table table = DatabaseBuilder.open(new File("filename")).getTable("tablename");
righe.add(0);
for(Row row : table) {
String articolo=row.get("ColName").toString();
Try this class forename and connection URL.Add the below jar files to your projects:
commons-lang.jar,commons-logging.jar,hsqldb.jar,jackcess.jar,ucanaccess.jar
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
//change the path with your own accdb file
String URL = "jdbc:ucanaccess://D:\\projects\\test.accdb";
Connection con = DriverManager.getConnection(URL);

Categories