tags:

views:

85

answers:

6

Hey all

i am trying to install JDBC but i dont know how, when you only have the jar file, i copied it to my java ext folder but it keep giving me an error, can anyone show me how to complete install the driver and use it?

below is the codes that i used

import java.sql.*;
   public class Test1
   {
       public static void main (String[] args)
       {
String url = "jdbc:mysql://localhost:3306/sabayafr_sabmah";
String username = "root";
String password = "ma";
Connection connection = null;
try {
    System.out.println("Connecting database...");
    connection = DriverManager.getConnection(url, username, password);
    System.out.println("Database connected!");
} catch (SQLException e) {
    System.err.println("Cannot connect the database!");
    e.printStackTrace();
} finally {
    System.out.println("Closing the connection.");
    if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}

       }
   }

And below is the Response that i get

Cannot connect to database server

Update # 3

C:\Users\AlAsad\Desktop>java -cp .;mysql-connector-java-5.0.8-bin.jar Test1
Connecting database...
Cannot connect the database!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
sabayafr_sabmah
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at Test1.main(Test1.java:12)
Closing the connection.
A: 

Try putting your .jar file in the classpath.

OscarRyz
A: 

The library that contains the Driver (net.sourceforge.jtds.jdbc.Driver) needs to be on the classpath.

Assuming you start your application with

java Test1

then simply do

java -cp .;driver.jar Test1

where 'driver.jar' should be exchanged with the filename (relative or full path) of your database driver lib.

EDIT

A classpath tutorial will exceed the comments section below this question. Please take a cup of coffee and look at this page. It will most likely help you to continue.

Andreas_D
Hey Andreas_D when i added to my java application `java -cp .;driver.jar my.product.Class` i get and error
Mahmoud
@Mahmoud - you know that my fragments are just examples to explain the general approach !? Copying the exact line into your environment will not work.
Andreas_D
i didn't copy the exact line i copied the method and changed to the real information, but i keep not getting what is my.product.class at the end of the method
Mahmoud
Ah, sorry, replace `my.product.Class` with `Test1` (the class that contains the main method).
Andreas_D
I am getting this error `C:\Users\AlAsad>java -cp .;driver.jar Test1``Exception in thread "main" java.lang.NoClassDefFoundError``Caused by: java.lang.ClassNotFoundException: Test1`` at java.net.URLClassLoader$1.run(Unknown Source)`` at java.security.AccessController.doPrivileged(Na`` at java.net.URLClassLoader.findClass(Unknown Sour` ` at java.lang.ClassLoader.loadClass(Unknown Source`` at sun.misc.Launcher$AppClassLoader.loadClass(Unk`` at java.lang.ClassLoader.loadClass(Unknown Source`Could not find the main class: Test1. Program will exit.
Mahmoud
Hey @Andreas_D i have update the question
Mahmoud
+1  A: 

On the other hand, if you are using an IDE such as Netbeans or Eclipse you can add the jar file as a resource to the project.

npinti
Your advice is correct, but I hate it when people do things with IDEs that they don't understand. Everyone who uses Java ought to know command line and CLASSPATH.
duffymo
+5  A: 

You're trying to connect MySQL with the URL of a jTDS JDBC driver which is designed specifically for Microsoft SQL Server. This ain't ever going to work. Even not when you fix the current problem by placing the JAR file in classpath.

You really need the MySQL JDBC driver. Also see this answer for a short but complete tutorial

BalusC
Hey @BalusC i totall understand i used that method but i am confused on how to install the driver to my class
Mahmoud
You need to add the JAR file containing the JDBC driver to the runtime classpath. The linked answer explains that in detail. If you're using an IDE, just add JAR file as *Library* to *Build Path*. If you're using `java.exe`, then you need to specify its path in `-cp` argument. The path should be either absolute, e.g. `c:/path/to/mysql-connector.jar` or relative to current working directory, e.g. `mysql-connector.jar` when the JAR file is in the same folder from where you execute the `java.exe`.
BalusC
I have updated my Question please look into it, at the moment i am getting cant connect to database
Mahmoud
As per your edit: you should **never** suppress exceptions without a good reason. Add `e.printStackTrace()` or just `throw e` after `System.err.println()`. You'll get valuable information about the exception type and message. The `try` block namely contains several lines of code which can throw completely different exceptions. Apart from a missing driver, the URL may for instance be wrong or the user may not be authorized.
BalusC
After adding `e.printStackTrace();` it appears that the drivers is still missing after adding `java -cp driver.jar Test1`
Mahmoud
Then the driver is not there where you expect it is, or the path/filename is plain wrong. It's at least certainly not named `driver.jar`. It's something like `mysql-connector-java-5.1.7-bin.jar`. Download the ZIP file containing MySQL JDBC driver, extract it and you'll see a JAR file. This needs to be added to the runtime classpath.
BalusC
sorry that was my mistake i was adding the wrong driver, but still i am getting an error where i posted it up on update #2
Mahmoud
Add the path of `Test1` to the classpath as well :) Assuming it's the current working directory, add `.` and separate the classpath paths using semicolon `;`. I.e. `java -cp .;mysql-connector.jar Test1`.
BalusC
please look at the error on update #3
Mahmoud
You forgot to load the driver using `Class#forName()`. Please look at [the linked answer](http://stackoverflow.com/questions/2839321/java-connectivity-with-mysql/2840358#2840358) for a short but complete tutorial.
BalusC
didn't understand?
Mahmoud
Run `Class.forName("com.mysql.jdbc.Driver");` *before* `DriverManager#getConnection()` call. It's in a separate `try` block in the linked answer. Please breathe deep and carefully take the steps from top to bottom. Don't hurry ;)
BalusC
you are the master THANK YOU THANK YOU a million time man, now i can start with my project, your the best and i hope to learn from you
Mahmoud
You're welcome. Follow my answers and links to learn from me ;)
BalusC
+1  A: 

You certainly have JDBC problems, but the exception isn't telling you that. Read it again:

Exception in thread "main" java.lang.NoClassDefFoundError: Test1
Caused by: java.lang.ClassNotFoundException: Test1

It's your Test1.class that it can't find, not the JDBC driver.

You should not be copying anything into the jre/lib/ext directory. That's for library extensions, not JDBC JARs. It wasn't meant as a crutch for people who don't understand how CLASSPATH works.

I'd write it more like the following. Those close methods will come in handy.

When I run it on my machine, adding the MySQL JDBC JAR to my CLASSPATH, I get the following result:

C:\java -classpath .\mysql-connector-java-5.1.6-bin.jar; persistence.utils.DatabaseUtils
product: MySQL
version: 5.1.24-rc-community
major  : 5
minor  : 1

Here is the source code:

package persistence.utils;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseUtils
{
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/contacts";
    public static final String USERNAME = "contacts";
    public static final String PASSWORD = "contacts";

    public static void main(String[] args)
    {
        Connection connection = null;

        try
        {
            String driver = ((args.length > 0) ? args[0] : DRIVER);
            String url = ((args.length > 1) ? args[1] : URL);
            String username = ((args.length > 2) ? args[2] : USERNAME);
            String password = ((args.length > 3) ? args[3] : PASSWORD);

            connection = getConnection(driver, url, username, password);

            DatabaseMetaData metaData = connection.getMetaData();

            System.out.println("product: " + metaData.getDatabaseProductName());
            System.out.println("version: " + metaData.getDatabaseProductVersion());
            System.out.println("major  : " + metaData.getDatabaseMajorVersion());
            System.out.println("minor  : " + metaData.getDatabaseMinorVersion());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            close(connection);
        }
    }


    public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
    {
        Connection connection = null;

        Class.forName(driver);
        connection = DriverManager.getConnection(url, username, password);

        return connection;
    }

    public static void close(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void close(Statement statement)
    {
        try
        {
            if (statement != null)
            {
                statement.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet resultSet)
    {
        try
        {
            if (resultSet != null)
            {
                resultSet.close();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void rollback(Connection connection)
    {
        try
        {
            if (connection != null)
            {
                connection.rollback();
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }
}
duffymo
Check the question edit history. He edited his question a lot of times, removing/replacing the original coding and problems with every sort of new problem he encountered. +1 regardless for the effort of explaining the "current" problem :)
BalusC
+1  A: 

'I am trying to install JDBC'

You don't have to install JDBC. It is part of the JDK & JRE.

EJP