How to connect my Access Database using Java - java

I have the following code
import java.sql.*;
public class UserLogin {
public static void main(String[] args) {
try {
// Load MS accces driver class
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\AGENDAS\\Agenda.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "Java2016", "Java2016");
System.out.println("Connection Succesfull");
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
and it throws the next error
Got an exception!
sun.jdbc.odbc.JdbcOdbcDriver
How can I make the connection?

If you already use JDK8, I suppose the exception you get is a "class not found" exception. But since you did not post the full stack trace, it is not sure - yet, the class name in the output is a strong pointer in that direction.
Please check the source of your initialization of the JDBC URL, I would be interested. In the driver docs, this style is not listed:
9.3.5 What Is the JDBC URL Supported by the Bridge? The Bridge driver uses the odbc subprotocol. URLs for this subprotocol are of the
form:
jdbc:odbc:<data-source-name>[<attribute-name>=<attribute-value>]*
For example:
jdbc:odbc:sybase
jdbc:odbc:mydb;UID=me;PWD=secret
jdbc:odbc:ora123;Cachesize=300
http://download.oracle.com/otn_hosted_doc/jdeveloper/904preview/jdk14doc/docs/guide/jdbc/getstart/bridge.doc.html
Additionally, this is what I found on the state of the ODBC driver.
Status of the JDBC-ODBC Bridge
The JDBC-ODBC Bridge should be considered a transitional solution; it
will be removed in JDK 8.
http://docs.oracle.com/javase/7/docs/technotes/guides/jdbc/bridge.html
Since you are currently starting the project, it seems wise not to use the JDBC-ODBC bridge. Instead use JDK8 and find a solution involving SQL.Server express edition...

Since you are using Access i suggest using UCanAccess which is an open-source Java JDBC driver implementation that allows java developers and jdbc client programs to read/write Microsoft Access database (.mdb and .accdb files).
I think it's simpler and has more support than the traditional JDBC-ODBC bridge.
After downloading the UCanAccess driver, this is how you can set up your connection :
private Connection con ;
private Statement stmt;
public void connect ( String path ){
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
this.con = DriverManager.getConnection(path, "", "");
this.stmt = con.createStatement();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
catch (ClassNotFoundException e) {
System.err.println("classnotfoundException: " + e.getMessage());
}
}

Related

Can I connect to h2 embedded db without setting Class.forName("org.h2.Driver")?

Can I connect to h2 embedded db without setting Class.forName("org.h2.Driver") ?
I used only those parameters: url, login and pass
public static Connection getConnection() {
String url= ResourseHelper.getUrl();
String user= ResourseHelper.getUser();
String pass= ResourseHelper.getPass();
try {
return DriverManager.getConnection(url, user, pass);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
And than I create embedded database using this connection. And it works. Is it correct?
Yes, for Java 1.6 and newer, Class.forName("org.h2.Driver") is no longer needed. This is due to a change in JDBC 4.0. For details, see Getting Connected Becomes Easier.

Unload the jdbc sql server drivers

I load JDBC SQL Server drivers to connect to a database after the whole process I want to unload all the registered drivers
To register the drivers I use
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
How can I deregister all these drivers?
I tried the following but it seems not to be working
Enumeration<Driver> drivers = DriverManager.getDrivers();
while(drivers.nextElement() != null){
Driver d = drivers.nextElement();
try {
DriverManager.deregisterDriver(d);
} catch (SQLException e) {
e.printStackTrace();
}
}
I get the following exception
java.util.NoSuchElementException: Vector Enumeration
Edit
Now I get the following error when I run another task which also needs a connection to database using JDBC
WARNING: Failed to load the sqljdbc_auth.dll cause : Native Library C:\sqljdbc_4.0\enu\auth\x86\sqljdbc_auth.dll already loaded in another classloader
any idea?
You have to ensure there's an element with hasMoreElements() before using it with nextElement().
See also the javadoc: https://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html

When working with tomcat, how are JDBC Drivers loaded?

I am using Eclipse and tomcat 7. I have little experience with either product and for that matter Java itself. I was trying to connect to a derby database from a Servlet. Initially, all I had in my doGet() is the following:
conn = DriverManager.getConnection(connectionURL);
I have connectionURL defined as
static private String connectionURL = "jdbc:derby://localhost:1527/seconddb";
Then I added the following to the Build Path and Deployment Assembly.
C:\DERBY\db-derby-10.10.1.1-bin\lib\derbyclient.jar
That is all I did. I sort of assumed that Tomcat will find the driver class and load it. I got the following error
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/seconddb
Then I went on to add the following code in doGet() to load the driver class:
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Now it worked. I thought that after Java 1.4 there was no need to explicitly load JDBC driver class. So what am I doing wrong here? I have given the entire code below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
try {
conn = DriverManager.getConnection(connectionURL);
//DriverManager.getConnection("jdbc:derby://localhost:1527/testdb;create=true");
}
catch (SQLException e) {
e.printStackTrace();
}
PrintWriter p = response.getWriter ();
p.println("Connected to database");
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
I am using java 1.7
I cannot really explain why, but here is how I do :
if the driver is located in the war, I must call Class.forName("...Driver"); in in initialization method somewhere in the web application.
if the driver is located in Tomcat libraries, it is automacally loaded when I need it.
I know it's more a rule of thumb than a clear explaination, but my knowledge in class loading does not allow me to a better answer ...
Your Derby driver doesn't support the JDBC 4 auto-loading, so you have to do it manually. Try to find a more up to date version.
I could be wrong here but in your second code sample connectionURL
static private String connectionURL = "jdbc:derby://localhost:1527/seconddb";
doesn't include "create=true"; to complete the statement. In your full code sample it's included, but commented out.

Could not load the driver java.sql.SQLException: No suitable driver found for jdbc

I have a problem with connecting my java and mysql database was working fine yesterday but now is not working here is my code.
public static void main(String[] args) {
try
{
Class.forName ("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System.out.println ("Could not load the driver");
}
String user, pass, host, database;
user = "Michael";
pass = "Blaine22";
host = "localhost";
database = "maintenance_work";
Connection conn = DriverManager.getConnection
("jdbc:mysql://"+host+":3306/"+database, user, pass);
conn.setAutoCommit(false);
//Menu code:
appSchoolMaintenance newWork = new appSchoolMaintenance();
newWork.statement1(); // opens the start method
}
Add MySQL JDBC driver (you can get it here: http://dev.mysql.com/downloads/connector/j/) to application's classpath and remove unnecessary piece of code:
try
{
Class.forName ("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
System.out.println ("Could not load the driver");
}
You can try to connect directly with MySQL JDBC driver
com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
Connection conn = driver.
connect("jdbc:mysql://localhost/test?user=root&password=root", null);
if this code does compile you are missing MySQL JDBC driver on the classpath
Started to work again - tried all the suggestions but started working again no rhyme or reason to it! thanks for the help though

Java Wont connect to database no matter what driver

import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath

Categories