Using mysql from Xampp for java jdbc program

dhpratik picture dhpratik · Nov 28, 2012 · Viewed 28.6k times · Source

I have Xampp installed on my pc with mysql database. now i wish to use this mysql database for my java JDBC program. For that i have writen following program.

package mysqltype4driverdemo;

import java.sql.*;
import java.util.*;


public class MysqlType4DriverDemo {

    public static void main(String[] args)throws SQLException {
        String url="jdbc:mysql://localhost:3306/mysql";
        Properties prop=new Properties();
        prop.setProperty("user","root");
        prop.setProperty("password","");
        Driver d=new com.mysql.jdbc.Driver();
        Connection con = d.connect(url,prop);
        if(con==null)   {
            System.out.println("connection failed");
            return;
        }
        DatabaseMetaData dm =con.getMetaData();
        String dbversion=dm.getDatabaseProductVersion();
        String dbname=dm.getDatabaseProductName();
        System.out.println("name:"+dbname);
        System.out.println("version:"+dbversion);

    }
}

but it says "package com.mysql.jdbc" does not exists. P.S. : i am using netbeans 7.2.x IDE on windows XP platform

Answer

RobertB picture RobertB · Nov 29, 2012

It appears that you might have tried putting the library on the global CLASSPATH. For Netbeans projects, that's not quite right. You need to add the appropriate library(ies) to the project using Netbeans's library facility.

  1. Right-click on the project's root node in the Projects tab.
  2. In the pop-up context menu, click on Properties (on the bottom of the menu).
  3. Click on Libraries under Categories:. You should see the following screen: Netbeans Project Properties Dialog: Libraries
  4. Click on the Add Library... button.
  5. Under Global Libraries click on MySQL JDBC Driver and then click the Add Library button.
  6. Click on OK.

You should be good to go.

If you need a specific version of the driver, you can download it, and then after clicking on Add Library... you can click on Create... to add the downloaded version to your library repository. You'd then remove the default JDBC Driver from the project, and add the library containing the specific version.

I tried this out myself using your code and a newly-created project. No additional imports needed, and the default driver included with the Netbeans distro should be good enough unless you need a specific version for your project.