Getting Connected for the First Time with JDBC

Hello everyone. I am trying to make my first database connection to a mysql database with Java. I am using jdk 1.5.0, MySQL 4.1.11 nt, and I think I have the freshly downloaded driver C:\jdk1.5.0\jre\lib\ext\mysql-connector-java-3.0.16-ga-bin.jar" installed in the right spot. When I try to run the following code...
package dbfinder;
import java.sql.*;
import javax.sql.*;
import com.sun.rowset.JdbcRowSetImpl;
import javax.sql.rowset.JdbcRowSet;
import java.sql.ResultSetMetaData;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
public class DatabaseConnector {
public DatabaseConnector() {
public static void main(String args[]){
Connection connection;
Statement statement;
// ResultSet resultSet;
// ResultSetMetaData metaData;
String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
String DATABASE_URL = "jdbc:mysql://localhost/state_crime";
String USER = "cis695d";
String PASSWORD = "cis695d";
JdbcRowSet rowSet = new JdbcRowSetImpl();
try {
Class.forName(DATABASE_DRIVER); // load database driver
System.out.println("class loaded");
rowSet.setUrl("DATABASE_URL");
rowSet.setUsername(USER);
rowSet.setPassword(PASSWORD);
rowSet.setCommand("Select * FROM state_crime_rates");
rowSet.execute();
ResultSetMetaData metaData = rowSet.getMetaData();
int numberOfColumns;
numberOfColumns = metaData.getColumnCount();
System.out.println(numberOfColumns);
} catch(SQLException sqlException){
sqlException.printStackTrace();
System.exit(1);
catch(ClassNotFoundException classNotFound){
classNotFound.printStackTrace();
System.exit(1);
I get the following exception...
java.sql.SQLException: No suitable driver
     at java.sql.DriverManager.getConnection(DriverManager.java:545)
     at java.sql.DriverManager.getConnection(DriverManager.java:171)
     at com.sun.rowset.JdbcRowSetImpl.connect(JdbcRowSetImpl.java:618)
     at com.sun.rowset.JdbcRowSetImpl.prepare(JdbcRowSetImpl.java:630)
     at com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:526)
     at dbfinder.DatabaseConnector.main(DatabaseConnector.java:44)
Does anyone have any ideas? Is it my code? Is there a different driver I should use? Any help would be greatly appreciated.

Hello everyone. I am trying to make my first
database connection to a mysql database with Java. I
am using jdk 1.5.0, MySQL 4.1.11 nt, and I think I
have the freshly downloaded driver
C:\jdk1.5.0\jre\lib\ext\mysql-connector-java-3.0.16-ga
-bin.jar" installed in the right spot. You shouldn't be putting that JAR in jre/lib/ext, even if you've found some docs to tell you to do it. Only language extensions (e.g., packages that begin w/javax) belong there.
I get the following exception...
java.sql.SQLException: No suitable driver
Does anyone have any ideas? Is it my code? Is there
a different driver I should use? Any help would be
greatly appreciated.The driver is correct. The class loader found it, even though I think you should use the -classpath option to find the JAR.
It's your code.
What are you doing with all that RowSet stuff?
This works. Study it:
import java.sql.*;
import java.util.*;
* Command line app that allows a user to connect with a database and
* execute any valid SQL against it
public class DataConnection
    public static final String DEFAULT_DRIVER   = "sun.jdbc.odbc.JdbcOdbcDriver";
    public static final String DEFAULT_URL      = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
    public static final String DEFAULT_USERNAME = "admin";
    public static final String DEFAULT_PASSWORD = "";
    public static final String DEFAULT_DRIVER   = "com.mysql.jdbc.Driver";
    public static final String DEFAULT_URL      = "jdbc:mysql://localhost:3306/hibernate";
    public static final String DEFAULT_USERNAME = "admin";
    public static final String DEFAULT_PASSWORD = "";
    /** Database connection */
    private Connection connection;
     * Driver for the DataConnection
     * @param command line arguments
     * <ol start='0'>
     * <li>SQL query string</li>
     * <li>JDBC driver class</li>
     * <li>database URL</li>
     * <li>username</li>
     * <li>password</li>
     * </ol>
    public static void main(String [] args)
        DataConnection db = null;
        try
            if (args.length > 0)
                String sql      = args[0];
                String driver   = ((args.length > 1) ? args[1] : DEFAULT_DRIVER);
                String url      = ((args.length > 2) ? args[2] : DEFAULT_URL);
                String username = ((args.length > 3) ? args[3] : DEFAULT_USERNAME);
                String password = ((args.length > 4) ? args[4] : DEFAULT_PASSWORD);
                System.out.println("sql     : " + sql);
                System.out.println("driver  : " + driver);
                System.out.println("url     : " + url);
                System.out.println("username: " + username);
                System.out.println("password: " + password);
                db = new DataConnection(driver, url, username, password);
                System.out.println("Connection established");
                Object result = db.executeSQL(sql);
                System.out.println(result);
            else
                System.out.println("Usage: db.DataConnection <sql> <driver> <url> <username> <password>");
        catch (SQLException e)
            System.err.println("SQL error: " + e.getErrorCode());
            System.err.println("SQL state: " + e.getSQLState());
            e.printStackTrace(System.err);
        catch (Exception e)
            e.printStackTrace(System.err);
        finally
            if (db != null)
                db.close();
            db = null;
     * Create a DataConnection
     * @throws SQLException if the database connection fails
     * @throws ClassNotFoundException if the driver class can't be loaded
    public DataConnection() throws SQLException,ClassNotFoundException
        this(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
     * Create a DataConnection
     * @throws SQLException if the database connection fails
     * @throws ClassNotFoundException if the driver class can't be loaded
    public DataConnection(final String driver,
                          final String url,
                          final String username,
                          final String password)
        throws SQLException,ClassNotFoundException
        Class.forName(driver);
        this.connection = DriverManager.getConnection(url, username, password);
     * Get Driver properties
     * @param database URL
     * @return list of driver properties
     * @throws SQLException if the query fails
    public List getDriverProperties(final String url)
        throws SQLException
        List driverProperties   = new ArrayList();
        Driver driver           = DriverManager.getDriver(url);
        if (driver != null)
            DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
            if (info != null)
                driverProperties    = Arrays.asList(info);
        return driverProperties;
     * Clean up the connection
    public void close()
        close(this.connection);
     * Execute ANY SQL statement
     * @param SQL statement to execute
     * @returns list of row values if a ResultSet is returned,
     * OR an altered row count object if not
     * @throws SQLException if the query fails
    public Object executeSQL(final String sql) throws SQLException
        Object returnValue;
        Statement statement = null;
        ResultSet rs = null;
        try
            statement = this.connection.createStatement();
            boolean hasResultSet    = statement.execute(sql);
            if (hasResultSet)
                rs                      = statement.getResultSet();
                ResultSetMetaData meta  = rs.getMetaData();
                int numColumns          = meta.getColumnCount();
                List rows               = new ArrayList();
                while (rs.next())
                    Map thisRow = new LinkedHashMap();
                    for (int i = 1; i <= numColumns; ++i)
                        String columnName   = meta.getColumnName(i);
                        Object value        = rs.getObject(columnName);
                        thisRow.put(columnName, value);
                    rows.add(thisRow);
                returnValue = rows;
        else
            int updateCount = statement.getUpdateCount();
            returnValue     = new Integer(updateCount);
        finally
            close(rs);
            close(statement);
        return returnValue;
     * Close a database connection
     * @param connection to close
    public static final void close(Connection connection)
        try
            if (connection != null)
                connection.close();
                connection = null;
        catch (SQLException e)
            e.printStackTrace();
     * Close a statement
     * @param statement to close
    public static final void close(Statement statement)
        try
            if (statement != null)
                statement.close();
                statement = null;
        catch (SQLException e)
            e.printStackTrace();
     * Close a result set
     * @param rs to close
    public static final void close(ResultSet rs)
        try
            if (rs != null)
                rs.close();
                rs = null;
        catch (SQLException e)
            e.printStackTrace();
     * Close a database connection and statement
     * @param connection to close
     * @param statement to close
    public static final void close(Connection connection, Statement statement)
        close(statement);
        close(connection);
     * Close a database connection, statement, and result set
     * @param connection to close
     * @param statement to close
     * @param rs to close
    public static final void close(Connection connection,
                                   Statement statement,
                                   ResultSet rs)
        close(rs);
        close(statement);
        close(connection);
}%

Similar Messages

  • I'm trying to use my iPad mini for the first time with a previous apple ID and password but it will not connect to iTunes but I can download apps from my iPhone using the same appleID and password and it works on my iphone...PLEASE HELP NOW

    I'm trying to use my iPad mini for the first time with a previous apple ID and password but it says "iTunes is not working try again"...it allowed me to download an app on my iPhone using the same apple ID &amp; password but all my apps are in "Waiting Status" on my iPad mini because it says "iTunes is not working"...PLEASE HELP ME NOW!!!

    Previous user installed iOS 7 beta on that iPhone.
    Take it back and get your money returned. You
    are running into a new security feature. Whoever owns
    the ID that it is asking for is the only person who can
    remove the security. That iPhone is worthless to you.

  • Oracle XE 10g connect for the first time

    I have just installed Oracle10 g express edition on Windows XP service pack 3, when trying to connect for the first time
    I get the ORA-12631 message error when trying to connect!!
    SQL> connect system
    Immettere la password:
    ERROR:
    ORA-12631: Recupero nome utente non riuscito
    Can anyone help me?

    sorry here is:
    Microsoft Windows XP [Version 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.
    C:\>set
    ALLUSERSPROFILE=C:\Documents and Settings\All Users
    ambiente=AC
    APPDATA=C:\Documents and Settings\UR00780.HD01\Application Data
    CLIENTNAME=Console
    CommonProgramFiles=C:\Program Files\Common Files
    COMPUTERNAME=ACMI1252
    ComSpec=C:\WINDOWS\system32\cmd.exe
    cstella=VERONA
    FP_NO_HOST_CHECK=NO
    fserver=ACSWDWV01
    HOMEDRIVE=H:
    HOMEPATH=\
    HOMESHARE=\\acnas200.intranet.unicredit.it\UR00780
    KITID=AC
    LOGONSERVER=\\USADSW340
    LSERVER=ACSWDWV01.hd01.unicreditgroup.eu
    NUMBER_OF_PROCESSORS=2
    OS=Windows_NT
    Path=C:\oraclexe\app\oracle\product\10.2.0\server\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program
    Files\Microsoft SQL Server\80\Tools\BINN;C:\Program Files\IBM\Personal Communications\;C:\Program Files\IBM\Trace Facil
    ity\;C:\Program Files\Symantec\pcAnywhere\;C:\PROGRA~1\IBM\CLIENT~1;C:\PROGRA~1\IBM\CLIENT~1\Shared;C:\Program Files\Int
    el\DMIX;c:\Program Files\Microsoft SQL Server\90\Tools\binn\
    PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
    PCOMM_Root=C:\Program Files\IBM\Personal Communications\
    PROCESSOR_ARCHITECTURE=x86
    PROCESSOR_IDENTIFIER=x86 Family 6 Model 37 Stepping 2, GenuineIntel
    PROCESSOR_LEVEL=6
    PROCESSOR_REVISION=2502
    ProgramFiles=C:\Program Files
    PROMPT=$P$G
    SESSIONNAME=Console
    SystemDrive=C:
    SystemRoot=C:\WINDOWS
    TEMP=C:\DOCUME~1\UR0078~1.HD0\LOCALS~1\Temp
    TMP=C:\DOCUME~1\UR0078~1.HD0\LOCALS~1\Temp
    USERDNSDOMAIN=HD01.UNICREDITGROUP.EU
    USERDOMAIN=HD01
    USERNAME=UR00780
    USERPROFILE=C:\Documents and Settings\UR00780.HD01
    windir=C:\WINDOWS
    C:\>

  • HT4859 How long should it take to back up iphone for the first time with about 6 gigs?

    How long should it take to back up iphone for the first time with about 6 gigs?

    Welcome to the Apple Community.
    The first back up to iCloud may take some considerable time. Just how long isn't really possible to say without knowing how much is in your back up and your connection speed.
    What many people don't realise is that upload speeds are often significantly less than download speeds, so for example a user may have a download speed of 40 Mbps, but only 1 Mbps for uploading. As a rough guide it will take around 2 ¼ hours to upload 1 GB of data at 1 Mbps.

  • I live in Italy and I am trying to buy an App, for the first time with my iphone4...in the past only downloaded free apps free apps; I have a US Visa card and it is not accepted by italian Itunes...what can I do to do my purchases?

    I live in Italy and I am trying to buy an App, for the first time with my iphone4...in the past only downloaded free apps free apps; I have a US Visa card and it is not accepted by italian Itunes...what can I do to do my purchases?

    On the apple website that is correct i beleive.... but i have an italian american express and am able to purchase stuff here in the US.
    I mean, i dont think it really matters

  • I am getting this for the first time when i sync .iphone 3gs error message itunes could not sync calendars to the iphone because the sync server failed to sync iphone

    i am getting this for the first time when i sync .iphone 3gs error message itunes could not sync calendars to the iphone because the sync server failed to sync iphone

    I have tried the suggestion to reset the sync log to no avail. Anyone have another idea? This just started after I downloaded 4.3.5.

  • How can I delete photos from my ipad that came in when I connected for the first time to my pc?

    how can I delete photos from my ipad that came in when I connected for the first time to my pc? HELP

    Photos that were synced from your computer using iTunes can only be deleted by de-selecting them from the folder from where they were synced -  and then re-syncing.
    Connect the iPad to the PC and launch iTunes.
    Click on the iPad name on the left side under devices.
    Click on the Photos Tab on the right.
    If you want to remove all of the Photos - uncheck the Sync Photos from Heading
    Click on Apply in the lower right corner of iTunes
    If you are using iTunes 11 - this will be helpful, Setting up syncing in Windows.
    http://support.apple.com/kb/PH12313

  • I decided to backup for the first time with icloud yesterday, and lost all my phone contacts! I am panicking, because the backup says 0, and I checked the internet account on my pc, and it's only showing email addresses from my hotmail account. What to do

    I decided to backup for the first time with icloud yesterday, and lost all my  phone contacts! I am panicking because the backup is saying 0 and I checked the internet account on my pc,and it's only showing email addresses from my hotmail account. What to do? How to recover them!

    Have they also gone from iCloud.com when you log in from a computer.

  • What can I do to make sure all my information (Notes Included) transfers to my new MacBook Pro when connecting for the first time?

    I am about to connecting my Iphone to my new Macbook Pro for the first time. I just want to make sure that all my information: contacts, messages, notes, everything will still be on my phone. I just dont want to connect then find out I lost everything on my phone.
    Help! I am really bad with technology...

    When you first sync with a new iTunes library iTunes will delete any iTunes media from your phone and replace it with the media in the library being synced with.  iTunes media includes things like apps, music, movies, tv shows, podcasts, books, custom ringtones and photos synced to your phone from a computer.  If you are also syncing your contacts and calendars with your computer it will replace the ones on your phone with those on your computer.  If your iTunes library, contacts, calendars and iPhoto are all empty, you will end up with all of these being empty on your phone.
    To preserve these you need to follow the steps in the linked article.  This will transfer purchased media from your phone to your iTunes library and transfer contacts and calendar entries to your Mac.  As discussed in the guide, it will not transfer music not purchased from the iTunes store (which can only be done using 3rd party software such as the ones discussed) or photos synced to your phone from another computer (which can be transferred to your computer using an app like PhotoSync).  These will need to done first or you will lose them, as discussed in the guide.

  • Signing up for the first time with no success..

    I was reluctant to get Ipad and mac services but this is making me frustrated. Using a New Ipad, I signed up for a new Id.. using my email and a password that I know very well. I go to sign in for the first time and I get Id has not been used before please select review and..... well I hit review and nothing happens.. I try to go direct to apple id services and it says either my email or my password is incorrect. I've already requested to new passwords used them and requested a verification email which I get and go to verify and it is not working.. VERY FRUSTRATING...
    Please help..

    Hi..
    Sorry you are having problems right off the bat ..
    Even though you just created a new Apple ID, try the suggestions here >  Using an existing Apple ID with the iTunes Store, Mac App Store, and iBooks Store
    If that doesn't help, contact Apple directly >  Contacting Apple for support and service

  • Setting up Mail for the first time with OSX Server 10.5.6

    I just got done reading the 100+ page mail services administration manual. A few things are unclear and I wanted to clear those up prior to embarking on my first adventure configuring mail services.
    The questions I have are the following:
    1. When using mail for incoming and outgoing, do I 'have' to use local DNS services or can I simply change the MX records by my DNS Provider?
    2. I have more than one IP on the server using the 'IP Alias' command. Will the mail server be able to distinguish the different mail domains base on IP Address, or will virtual domains need to be configured?
    3. If virtual domains need to be configured, is this configuration simple or is it semi complex?
    4. Provided the answer to questions two and three, what is the best configuration for the firewall settings on the server? Allow IMAP inbound, POP3, and SMTP? What else?
    Thanks in advance

    1. Mail service relies heavily on DNS. You may run your own DNS servers on the same network as your mail server or you can use a DNS provider to host your zone data including your MX record.
    2. Your server will listen on all available network devices by default. It will only accept those messages for the hosts that are listed in the general pane, the local host list, or the virtual domain list under the advanced pane. No virtual domains need to be configured if all users are real users (i.e. shows up in WorkGroup Manager).
    3. As stated in (2), you do not need virtual domains to receive e-mail for multiple hostnames or domain names, but you may want to do so if you want separate accounts with same usernames for different domains. E.g. [email protected] and [email protected] will go to two separate inboxes. It's not that difficult, but rather tedious if you already have a lot of e-mail accounts set up.
    4. You must allow SMTP through the firewall to receive mail from the outside world. Depending on your clients, you may open IMAP or POP. There are no other specific ports necessary for mail to work at this level... except for Submission (587). Many ISP's block port 25 for mail clients. You may want to use port 587 for submissions so that your mobile users don't have to switch back and forth between the two ports when they change locations. This is done by editing /etc/imapd.conf manually.

  • How to backup to TC for the first time with ethernet or USB

    I had an existing wireless network and have added a TC to it as a password protected wireless device. I can initiate a wireless backup using Time Machine from my desktop Mac, but anticipating that this will be a very long first backup, I'm trying to set up a wired first time backup using ethernet. So, I've plugged an ethernet cable between the desktop Mac and one of the ethernet ports on the TC and then switched off my desktop Airport connection. I was hoping that I could then just backup using TM, but the TC doesn't seem to be recognised.
    Can anyone tell me what to do? Presumably I'm doing something wrong because most people who have bought TCs are likely to have done their first backup through ethernet.

    amthie,
    Here are the steps I have used to perform the initial TC backup.
    *Using Time Capsule via Temporary Ethernet ONLY Connection*
    Connect one end of a Cat-5 Ethernet cable into one of the LAN ports of the TC (<•••>) NOT to the WAN port (wheel icon). Connect the other end to your Macs ethernet port.
    Next, go to System Prefs --> Network.
    At the top of the window note what “Location” you are currently using, as you will need to return to this setting later.
    Now, change “Location” to “Edit Locations”.
    Click the “+” button and create a new location named “Ethernet Only”.
    Click “Done”.
    In the Services Pane on the left, eliminate all other services using the “-” button leaving “Ethernet” only. If you choose to leave other services listed then al the very least move Ethernet to the top of the list using the Action Menu (gear button) at the bottom and "Set Service Order".
    Verify that “Configure” says “Using DHCP”.
    Click "Apply" in the lower right.
    You should be seeing an assigned IP Address and the Status should say “Connected”. The dot beside “Ethernet” should be green.
    Now begin your backup or transfer of files.
    You should still have internet access during this period.
    Once the backup/transfer is complete, remember to change the Network Prefs “Location” back to “Automatic”, or whatever setting it had originally been, to restore Airport connectivity.
    Cheers!

  • Using QuickTime 7 Pro for the first time with Windows. What can it do?

    Greetings,
    After spending almost two hours with Apple reps, I finally figured out where the controls are for QuickTime Pro. I have started to use Miraizon's Cinematize Pro 2 to extract clips as mpeg-4 files (a lot smaller than a QT movie, though maybe it can be made smaller if I compressed it, though I don't know how). Now I wish I knew exactly what I am able to do with my mpeg-4 clip once I've extracted it.
    So the question is, having a PC, Windows XP and QT 7 Pro, exactly what features does it have for editing? I opened a mpeg-4 with QT Player and of course have the following to choose from under the "edit" function: cut, copy, delete, select all,select none, trim to selection, add to movie, add to selection and scale, find and preferences. So please tell me at least what I can do with this program and at least how to begin.
    By the way, I have a website and use Microsoft FrontPage 2003. I have a combination of video types previously made and sent to me by others; some are .wmv, some are .mov. Now as I use Cinematize 2 Pro, I am creating mpeg-4s. This choice is made because I'd like to keep the file as small as possible without losing quality per se and also I want to reduce to a minimum the problems anyone visiting my site who wants to see the clip might have. Also you should know I insert the movie files onto my websie as plug-ins/MIME files.
    I'm new to the list and would greatly appreciate your help.
    Thanks!

    QuickTime Pro is a rather simple editing application and once you learn how to make a "selection" (letter i and o keys) and then fine tune it (Shift and right left arrow keys) you're on your way.
    You can also "scrub" through large files by using the J, K and L keys or copy/paste selections into new Player windows.
    Dozens of image, video and audio formats can be opened by QuickTime Pro and then "Exported" (converted) to other file formats. It can even open plain text files to use as "titles", narration text for the hearing impaired.
    The Windows version can also make "One Click" audio recordings (Mac version can make video and audio files). A simple way to add a narration track to your video. Since QuickTime .mov files can have up to 99 tracks and support about 27 languages you can make one file for many nations.
    QuickTime Pro is also a very powerful authoring tool.
    QuickTime Pro can even create files that view without a "box":
    http://homepage.mac.com/kkirkster/D/index.html
    Some of my QuickTime files and Web pages as examples:
    http://homepage.mac.com/kkirkster/03war/
    http://homepage.mac.com/kkirkster/RedneckTexasXmas/index.html
    It can also be used to make "presentation" files:
    http://homepage.mac.com/kkirkster/.Public/TouchofGrey.qtl
    What can it do? It's all up to your imagination.

  • Airport Extreme (802.1) cannot connect for the first time.

    Hi all!
    I got an Ubuntu running Wine and the Admin Utility For Windows. I am trying to connect (after a hard reset) to the Airport Extreme Base Station. But no matter what I do I cannot get through the default password (which is supposed to be 'admin' or 'public' ) Neither work - can't configure the router! Please advise!

    Do as it says. Your license is for Creative Suite, not Acrobat. You must activate the license by opening one of the other programs first.

  • Connecting for the first time

    New iPod Shuffle, 1 Gb.
    Manual in the box says connect Shuffle to dock, then plug dock into computer.
    iPodshuffle_FeaturesGuide.pdf downloaded from Apple says plug dock into computer, then connect Shuffle to dock.
    Anyone know how it should be done ?
    I don’t want to foul things up on first try.
    Thanks for any help.

    Your dock can remain connected to your computer to be used whenever you need to charge or sync your Shuffle. That said, connect the dock and then plug the Shuffle into the dock. (However, I really don't think the order of connection makes any difference.)

Maybe you are looking for