Connect Java to Access DB on network drive - java

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", "", "")

Related

DB Derby Database stops functioning once connected to DBeaver

Here is my application's code to create the database, connect to it, and make a table in the database called Accounts.
package eportfolio.application;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
*
* #author valeriomacpro
*/
public class HomePage extends javax.swing.JFrame {
public static String username;
public static String password;
public static int SelectedPost;
/**
* Creates new form HomePage
*/
public static boolean doesTableExists (String tableName, Connection conn)
throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
public HomePage() {
initComponents();
try
{
String databaseURL = "jdbc:derby:eportdatabase;create=true";
Connection con = DriverManager.getConnection(databaseURL);
Statement st = con.createStatement();
if (!doesTableExists("Accounts", con))
{
String sql = "CREATE TABLE Accounts (Username varchar(250), Password varchar(250)) ";
st.execute(sql);
System.out.println("Table Does Not Yet Exist!");
}
else if(doesTableExists("Accounts", con)) {
System.out.println("Table Already Exists!");
}
con.close();
} catch(SQLException e) {
do {
System.out.println("SQLState:" + e.getSQLState());
System.out.println("Error Code:" + e.getErrorCode());
System.out.println("Message:" + e.getMessage());
Throwable t = e.getCause();
while(t != null) {
System.out.println("Cause:" + t);
t = t.getCause();
}
e = e.getNextException();
} while (e != null);
}
}
Additionally, here is my code that interacts with the Accounts table.
try
{
String databaseURL = "jdbc:derby:eportdatabase;";
Connection con1 = DriverManager.getConnection(databaseURL);
Statement st = con1.createStatement();
String sql = " INSERT INTO Accounts VALUES ('"+txtNewUsername.getText()+"','"+txtNewPassword.getText()+"') ";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Account Info Saved!");
txtNewUsername.setText("");
txtNewPassword.setText("");
txtNewConfirm.setText("");
}
When I run the application, the code works fine. However, if I open DBeaver and connect it to my database, then the following error message comes up. Does not come up if DBeaver is closed, even if it is connected to the database.
Message:Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XJ040: Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
SQLState:XSDB6
Error Code:45000
Message:Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Why is this? Am I connecting the Database to DBeaver incorrectly? Or am I coding the database incorrectly in Netbeans? It could be that my drivers and db derby version are old, but I have not been able to find help on that online either. Also important to know that the table does show up in DBeaver, but does not update. I have to delete the database folder in my application's folder every time I want to use the application with DBeaver open. Any help appreciated.
By using this line of code:
String databaseURL = "jdbc:derby:eportdatabase;";
you are using Derby in the "embedded" configuration. With Embedded Derby, only one Java application at a time can use the database. Other applications that try to use it concurrently are rejected with the message
Another instance of Derby may have already booted the database
as you saw when you tried it.
There are other configurations in which Derby can be deployed and run; specifically there is a Client-Server configuration in which multiple applications may all run as clients, and may connect to the same Derby server, allowing the applications to run concurrently.
To learn more about these aspects of Derby, start here: https://db.apache.org/derby/docs/10.15/getstart/cgsquck70629.html

Java Application cannot connect to mysql database in openshift

everyone!
I'm using the free account of OpenShift by RedHat PaaS to host my java aplication. For tests, I created an aplication that just get two user info (login and password) in the index.jsp, then it search into database and redirect to the success page(message "Good morning/afternoot/night, ${user.name}") or a failure page (message "You're not registred"). I also created a database, called autenticacao, with one table called usuario (user) in phpMyAdmin and this works well in localhost. But in the openshift, my servlet receives a null 'usuario' (user) object from the method obter(String login, String senha), that should get a result of one select query. I think it doesnt create a database connection. I've really tried so hard to make it works, and seen too many solutions in foruns (also here in stackoverflow) and nothing works.
Im using some design patterns but I think it's not a problem.
This is my DatabaseLocator.java:`
/*
* 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 dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* #author Luiz
*/
public class DatabaseLocator {
private static DatabaseLocator instance = new DatabaseLocator();
public static DatabaseLocator getInstance() {
return instance;
}
private DatabaseLocator() {
}
public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String user = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
String password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
String url = System.getenv("OPENSHIFT_MYSQL_DB_URL");
String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
Connection conn
= DriverManager.getConnection(host+port+"/autenticacao",user,password);
return conn;
}
}
The error happens when I try create a connection in st = conn.createStatement(); part.
public Usuario obterUsuario(String login, String password) {
Usuario usuario = null;
Connection conn = null;
Statement st = null;
try {
conn = DatabaseLocator.getInstance().getConnection();
st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from usuario where login='" + login + "' and senha='" + password + "'");
rs.first();
usuario = instanciar(rs);
} catch (ClassNotFoundException cnf) {
} catch (SQLException ex) {
System.out.println(ex.getCause());
}
return usuario;
}
public static Usuario instanciar(ResultSet rs) throws SQLException, ClassNotFoundException {
Usuario usuario = new Usuario();
usuario.setLogin(rs.getString("login"));
usuario.setSenha(rs.getString("senha"));
//other rs fields that would be setted to user object
return user;
}
}
This code is in portuguese, so if any word doesnt make sense, you can ask me. I have some other classes, I can show it if you want.
So, how can I connect to my database? Can you help me? Thanks.
Are you still facing this problem? If yes then try to make your openshift application non-scalable if it's set to scalable and vise versa if not. I've encountered this before I just don't remember exactly. In your case, port-forwarding in openshift will help if you don't want to change the scalability of your application. I use Jboss Dev Studio for creating my jboss app in openshift, in case you also want jboss.
You need to change the line:
Connection conn = DriverManager.getConnection(host+port+"/autenticacao",user,password);
It should be:
Connection conn = DriverManager.getConnection("jdbc:mysql:"+host+":"+port+"/autenticacao",user,password);

MySQL issue using Netbeans

OK so I made a mysql database on godaddy.com
I made an admin table there with 3 fields, ID,Username and Password.
In my program I connected to the database and it shows me the tables so I know its connected(Netbeans)
I downloaded Java JDBC driver and put it in the library of my project.
However when I run the program I get this error:
package testdata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestData {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try
{
String Name = "rsg";
String Pass= "dfgd";
String Host = "blahhhhhhhhhhhhhhh";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="DELETE FROM ADMIN";
stmt.executeUpdate(query);
String sql = "SELECT * FROM ADMIN";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
rs.updateInt("ID", 1 );
rs.updateString("Username", "CHRIS");
rs.updateString("Password", "CHRIS");
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
error is:
java.sql.SQLException: No suitable driver found for ****THIS IS MY HostName****
at java.sql.DriverManager.getConnection(DriverManager.java:604)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at testdata.TestData.main(TestData.java:28)
add mysql conntector jar file in your classpath.
I thing it's an issue with your host address. Check how should it look in MySql documentation
use
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DatabaseUrl, DataDaseusername, DatabasePass);
example for DatabaseUrl is given below
jdbc:mysql://192.168.100.100/databasename
mysql-connector-java-5.1.22 download from mysql.com
Insure you have add the jar folder in your project.
I believe its is looking for com.mysql.jdbc.Driver
make sure your connection string is correct for an example "jdbc:mysql://remot-example-mysql999.servage.net:3306/databasename?zeroDateTimeBehavior=convertToNull";
Your JDBC connection string is not correct (you cannot simply use the hostname). You need to use a JDBC URL, which for MySQL takes the form:
"jdbc:mysql://<hostname>:<port>/<database>"
Where <port> is optional if your server is running on the default, and is also optional. Change your getConnection method to this:
connection = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "3306", "YourDBName"),
Name, Pass);
Replace "YourDBName" with the name of the database you are trying to connect to. You also need to have the MySQL driver JAR in your classpath.

JDBC Driver Loading error

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.

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