Accessing MySQL on NetBeans using JDBC, Part 1: Create a connection

This entry is part 1 of 2 in the series Accessing MySQL on NetBeans using JDBC

Accessing MySQL on NetBeans using JDBC, Part 1: Create a connection

This tutorial show you how to use NetBeans to connect MySQL by using MySQL Connector/J, MySQL AB’s JDBC Driver for MySQL.

I’ll divide into 2 parts:

  1. Part I : Create a connection
    This part which you’re reading shows about how to establish a connection between NetBeans and MySQL.
  2. Part II : Perform SQL Operations
    This part show how to perform some basic operations from NetBeans to MySQL. For instance, send querys as SELECT, INSERT, UPDATE to a database.


  • MySQL Connector/J, licensed under the GPL or a commercial license
    from MySQL AB.
  • NetBeans with JRE (Java Runtime Environment).

Step-by-Step guide

  1. Installation
    • Install NetBeans.
    • Download MySQL Connector/J, name ‘’. (The file name may differs depends on the version if you’ve downloaded from the Official Site at here.)
    • Extract the zip file to a folder, you’ll see file ‘mysql-connector-java-5.0.6-bin.jar’ which is the library file that we want. Just copy the file to the library folder, for example to “C:\Program Files\Java\jdk1.6.0_02\lib” directory.
      the library file
  2. Add JDBC Driver to the project on NetBeans (Add a library).
    Next, I create a new Java project on NetBeans named ‘TestMySQL’ and add ‘mysql-connector-java-5.0.6-bin.jar’ that I’ve just extracted from previous step to the project’s library.

    1. Create New Project called TestSQL.
      Create new NetBeans's project
    2. In Projects window, right click the project name and select Properties.
      Open project's properties
    3. Project Properties window appears. The Categories on left side, select Libraries. And on right side in Compile tab, click Add JAR/Folder.
      Add JAR file
    4. New Window appears, browse to the file ‘mysql-connector-java-5.0.6-bin.jar’ and click Open.
      Browse to the library file
    5. You’ll see the .jar file was added to the project. Click OK to finish.
      The library file was added
      Note: You should keep mysql-connector-java-5.0.6-bin.jar in the directory that you won’t delete it (ex. not in temp folder). May be in the same directory that keep common library files. If you delete the file without delete a link from the project, the project will show error about missing library.
  3. Connect to the database.
    Now I’m going to write some code to connect to MySQL database. I have configured MySQL service on localhost.

    1. I’m going to use Connection and DriverMapper Classes so I need to import libraries.
      import java.sql.*;
      Import classes to the project
    2. I’ll connect to MySQL Server on local machine, the mysql database(a default database in MySQL). In main method, add the following code.
      try {  
                  String connectionUrl = "jdbc:mysql://localhost/mysql?" + 
                  Connection con = DriverManager.getConnection(connectionUrl);
              } catch (SQLException e) {
                  System.out.println("SQL Exception: "+ e.toString());
              } catch (ClassNotFoundException cE) {
                  System.out.println("Class Not Found Exception: "+ cE.toString());

      The code explanation:

      • Class.forName(“com.mysql.jdbc.Driver”); means load the MySQL driver.
      • “jdbc:mysql://localhost/mysql?” + “user=root&password=123456”; is a connection string that tells to connect MySQL on localhost, select database named ‘mysql’ and user/password for MySQL server.
        If you would like to connecto to other database, simply change text ‘mysql’ after ‘localhost/’ to your database name.
      Connection code
    3. Compile and run the project. If no error occurs, it means that the connection has established successfully.
      Connected MySQL successful

Next part, I’ll show to how to perform some basic SQL operations to MySQL.

Series NavigationAccessing MySQL on NetBeans using JDBC, Part 2: Perform SQL Operations >>

208 Responses to “Accessing MySQL on NetBeans using JDBC, Part 1: Create a connection”

  1. Soleil Farah

    i’m doiong a basketball scoreboard with it control panel on javabeans so any idea about how to connect a java application to mysql! not connecting netbeans to mysql . i’m facing some difficulties in solving this problem so would you please provide me help or send me a useful tutorial about the subject ..
    thank you for your time

  2. Muhammad Farooq

    You above mentioned article is very informative. Especially for learners it is very helpful. Keep up and I am waiting for 2nd part.

  3. Soleil Farah

    hey all thank for your help!!!! i did the link according 2 this article and itis working..
    i have another question: Does anyone know how can i connect 2 different GUIs, i want 2 link a control panel with it corresponding basketball scoreboard, i want the data to change on scoreboard each time i change it from the soreboard..
    Thank you

  4. Soleil Farah

    sorry i want the data to change on the scoreboard each time i change it from the control panel.. :):):)

  5. linglom

    I’m not sure that I understand your question correctly. If you have data displayed on more than 1 output, I suggest using Timer to periodically update your data on each output.

  6. Soleil Farah

    Thank u Linglom!! the thing is i want to update the scoreboard each time i have an action performed on the control panel. I’m connecting the control to a database implemented on MySQL and i want the scoreboard to retieve data from the database each time i modify them from the control. this project is what we call an MVC model( Model View Controller)any IDEAs??????
    Thank u again for ur help..

  7. Alan

    Thanks for the example. For some reason I received the message: “SQL Exception: java.sql.SQLException: Access denied for user…”. I then reformatted the getConnection to be in the form of 3 arguments like this:
    String connectionUrl = “jdbc:mysql://localhost/”;
    Connection con = DriverManager.getConnection(connectionUrl, “User”, “Password”);
    where “User” and “Password” were registered in the MySQL server, and it connected fine. Also, I don’t have a db yet, so I left out the db name.
    Thanks again for taking the time to post your example.

  8. linglom

    To Soleil Farah,
    Sorry for late answer. You can implement Timer class to refresh your data on scoreboard on every x seconds.

    // create a timer, xxxx is time in millisecond
    Timer timer = new Timer(xxxx, new ActionListener( {

    public void actionPerformed(ActionEvent evt) {
    //refresh your scoreboard
    // start the timer

    To Alan,
    Thank you for sharing.

  9. linglom

    If you’are using SQL Authentication method as in my example, you have to store username and password somewhere in the program maybe in code or external configuration file.

    Another way, you can use Windows Authentication method which authenticate by using the current user’s credential (user that execute the application) so no need to specify username and password in application.

  10. Arnaud

    Hello, I’m a completely new to Java and netbeans, I downloaded the MySQL Connector J 5.1.6 and added the address of the file in my CLASSPATH `enviroment variables`(I’m using Windows XP) , but Netbeans wasn’t able to load the drivers to connect to MySQL.
    Any idea why?
    I have followed your example and it works very well. So just would like to know why this is not working with the CLASSPATH method out of curiosity!
    Thank you

  11. Yasir

    I had done it already using jdk directly but could not accomplish this without this tutorial. Thanks a lot.

  12. Khaled

    Thanks a lot PRO for this cool, tutorial.
    I have wasted a full day to know how to connect to an MySQL database using Linux UBUNTU, but I didn’t know how. But by reading your tutorial it made things very simple.


  13. sofien

    Hello people, just to inform you all, what is in this tutoriel are the basics…because to use a database in java you must includes the jdbc driver for the corresponding database server in the application classpath.
    I’m facing a problem which can’t let me remotely connect to MySQL i-e:I have an application installed on different employee computers and the database installed on a server. So i have to enable remote connection for all IP addresses to my mysql instance…any idea please?

  14. Danish Kamran

    Same as Yasir’s comment.Have done it through JDK but creat problem, when I run it through Netbeans. Now resolved.


  15. Arijit Chattopadhyay

    I am using RedHat Enterprise Linux 4, netbeans ide 6.0 and mysql 4.1.7. I have done all the abpve steps to connect my java application with mysql. Although the drvier is loaded successfully but the login process is unsuccessful but from the erminal it is possible to login into mysql with that username and password

  16. Budhi

    It is OK if i used jdbc:mysql://localhost:port/dbname but it always fails when I used jdbc:mysql://ip_address:port/dbname

    Why ? It almost 1 week i’m searching for solution, but I can’t get one.

  17. arc

    Budhi you have only 3 solutions:
    1) use SSL
    2) enable remote connections on your host (phpadmin, cpanel)
    3) use different environment (eg. php+mysql)

  18. gary

    great, thanks a million. Just started using netbeans, and the tip about importing the library for postgres was a life saver.

    thanks 🙂

  19. T

    Best explanation I’ve read so far…thanx!

    Netbeans 6.5 provides a very simple way for connecting to a database. Though I can’t seem to locate the connection object to execute queries on :/
    Have you tried it?

  20. sole

    hi ya,

    cheers for writing this tutorial. it’s very useful and it works just fine. if only i found this blog sooner, spent an entire weekend trying to connect to my mysql database without success…

    cheers again and keep up the good work mate

  21. inez

    I tried it and it’s still not working for me =( What should I do next? I’ve tried to copy the .jar file to each lib folder, both in jdk and jre.

  22. inez

    OK it was my fault. I typed the driver name “com.jdbc.mysql.Driver” when the right one is “com.mysql.jdbc.Driver”. So your suggestion works. Thank you very much. =D

  23. Maggie

    THANK YOU SO MUCH! I have been missing the “properties add JAR” step and this is the first time I have seen it after 2 days of looking online for a solution!

  24. Rani

    Hi I am working with MS Access & Netbeans 6.5.1- how do you
    a) display all records from the DB to a jTable – and to show changes made to records on the table.
    b) how do you add music to a program (Netbeans GUI and java code)
    c) how do program a print button – to print records from a MS DB.

    Your assistance will be greatly appreciated.

  25. manoj

    String connectionUrl = “jdbc:mysql://localhost/database_name?” +

    i m using same without using ny password.

  26. patrick

    Hi, I’m trying to connect but failed. I am working with Netbeans 6.7.1 and I’ve get Message: “ Connection refused : connect”
    Please tell me what is my problem

  27. linglom

    Hi, Patrick
    What SQL Server edition you are trying to connect to? If it is SQL Server Express, have you enable remote connection?

  28. Hareesh


    Using the snippet provided above I’m trying to retreive the contents of the Database table Person. I’ve already created the table using mysql.
    But as soon as I execute this I’m getting the following exception.

    ” SQL Exception: java.sql.SQLException: Operation not allowed after ResultSet closed ”

    The table created

    mysql> select *from Person;
    | name | id |
    | xyz | 5 |

    package testapp;
    import java.sql.*;

    public class Main {

    public static void main(String[] args) {
    Statement stmt;
    ResultSet Results;
    String FirstName = null,Id = null,printrow;

    try {
    String connectionUrl = “jdbc:mysql://localhost/mysql?” + “user=root&password=pwdpwd”;
    Connection con = DriverManager.getConnection(“jdbc:mysql://localhost/Customer”,”root”,”pwd”);
    String query=”Select *from Person”;


    System.out.println(“No Data returned”);


    printrow=FirstName+” “+Id;


    } catch (SQLException e) {
    System.out.println(“SQL Exception: “+ e.toString());
    } catch (ClassNotFoundException cE) {
    System.out.println(“Class Not Found Exception: “+ cE.toString());



  29. linglom

    Hi, Hareesh
    If you are still referencing to the ResultSet object, do not close the Statement object yet. For this example, move the code “stmt.close();” to the bottom after the do-while loop should fix the problem.

  30. pkmnambiar

    Hi Guys,

    I have NetBeans 6.5 IDE on ubuntu 9.04.
    Please tell me where to copy-paste jar file.

    Thanks in advance!

  31. linglom

    Hi, pkmnambiar
    You don’t need to place the jar file on java folder. You can place any folder you want because you will browse to the file later by yourself.

    For Linux, the default java path should be /usr/bin/java.

  32. shola

    i create tables of my mysql database using netbeans, but i cant find from where in netbeans can i set autoincrement or autonum property of a coloumn of my table? further that i couldnt find it so i created the tables and i would like to modify the tables to set autonum in them instead of making them again so plz help in both matters

  33. Ankit

    This information really helped me out.
    But as I compile, it says
    SQL Exception: java.sql.SQLException: Communication failure during handshake. Is there a server running on localhost:3306?
    BUILD SUCCESSFUL (total time: 4 seconds)

    It says Build is sccuessful but also says failure handshake. Can you please let me know if the connection is successful or not?


  34. linglom

    Hi, Ankit
    Try to change the authentication method at the MySQL server.

    set password for @ = old_password(‘‘);

  35. Fö a betűm

    Hey man!
    Thanks for this tutorial at last i have found a good one, a step by step one, not a “check the documentation” one.

  36. Alvin

    hi, I face some problems. Hope can get a solution. Thanks in advance.

    package my.test;
    import java.sql.*;
    import java.util.*;
    public class NewClass
    public static void main(String[] args)
    int a = 5;
    a= a^3;
    System.out.println(Math.pow(2, 4));
    DB db = new DB();
    Connection conn=db.dbConnect(
    “jdbc:mysql://localhost:3306/applet”, “root”, “password”);
    Statement query= conn.createStatement();
    query.executeQuery(“select * from tabletest where ID=\’3\'”);
    ResultSet rs = query.getResultSet();
    int count = 0;
    while ( ())
    int idVal = rs.getInt (“ID”);
    int recordX = rs.getInt (“RecordX”);
    int recordY = rs.getInt (“RecordY”);
    System.out.println (
    “id = ” + idVal
    + “, name = ” + recordX
    + “, category = ” + recordY);
    rs.close ();
    query.close ();
    System.out.println (count + ” rows were retrieved”);
    List list = new LinkedList();
    catch(Exception e)



    class DB
    public DB() {}

    public Connection dbConnect(String db_connect_string,
    String db_userid, String db_password)
    Connection conn = DriverManager.getConnection(
    db_connect_string, db_userid, db_password);

    return conn;

    catch (Exception e)
    return null;

  37. Alvin

    output shown at below:

    com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

    MESSAGE: Connection refused: connect

    STACKTRACE: Connection refused: connect
    at Method)
    at com.mysql.jdbc.StandardSocketFactory.connect(
    at com.mysql.jdbc.MysqlIO.(
    at com.mysql.jdbc.Connection.createNewIO(
    at com.mysql.jdbc.Connection.(
    at com.mysql.jdbc.NonRegisteringDriver.connect(
    at java.sql.DriverManager.getConnection(
    at java.sql.DriverManager.getConnection(
    at my.test.DB.dbConnect(
    at my.test.NewClass.main(


    Last packet sent to the server was 0 ms ago.
    at com.mysql.jdbc.Connection.createNewIO(
    at com.mysql.jdbc.Connection.(
    at com.mysql.jdbc.NonRegisteringDriver.connect(
    at java.sql.DriverManager.getConnection(
    at java.sql.DriverManager.getConnection(
    at my.test.DB.dbConnect(
    at my.test.NewClass.main(
    BUILD SUCCESSFUL (total time: 2 seconds)

  38. linglom

    Hi, Alvin
    It seems that you have 2 problems:

    1. Communications link failure due to underlying exception
    2. Connection refused: connect

    For the first problem, I suggest you follow this thread:
    CORRECT SOLUTION: Communications link failure due to underlying exception

    For the second problem, try to change the hostname in the connection string to ip address, try both and your network ip address.

    Hi, Nissy
    I’m not have experience with mobile application. But I think the code for mobile application should be simialr with this example.

  39. Faisal Yousuf

    Thank you very much. I could not connect programmaticly to MySQL even though I could connect through the Services tab. The solution is to add the JAR file that contains the MySQL Connector. You describes how to do that step. Once I added the JAR file, everything worked.

    Once again, thank you.

  40. steven

    i got this exception while compiling can any one say wat problem !!!
    MESSAGE: Connection refused: connect

  41. steven

    pls help me in this exception Have no FileObject for C:\Program Files\Java\jdk1.6.0_13\jre\lib\sunrsasign.jar
    Have no FileObject for C:\Program Files\Java\jdk1.6.0_13\jre\classes
    SQl EXCEPTIONcom.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

    MESSAGE: Connection refused: connect

    STACKTRACE: Connection refused: connect
    at com.mysql.jdbc.StandardSocketFactory.connect(
    at com.mysql.jdbc.MysqlIO.(
    at com.mysql.jdbc.Connection.createNewIO(
    at com.mysql.jdbc.Connection.(
    at com.mysql.jdbc.NonRegisteringDriver.connect(
    at java.sql.DriverManager.getConnection(
    at java.sql.DriverManager.getConnection(
    at testmysql.Main.main(


    Last packet sent to the server was 32 ms ago.
    BUILD SUCCESSFUL (total time: 2 seconds)

  42. Terrence

    hi.. i follow the instructions above but I arrive at this output.. What does it mean. help.!Thnx

    SQL Exception: java.sql.SQLException: Access denied for user ‘root’@’localhost’ (using password: YES)
    BUILD SUCCESSFUL (total time: 0 seconds)

  43. linglom

    Hi, Terrence

    The error message stated that you had provided with the wrong password for user ‘root’. You need to change user name and password to the correct one in the connection string.

  44. Kumar. S


    I was terrible upset for I was not able connect to Oracle DB using netbean. Your lesson part one and two has given me breather and I am so happy that I am able to connect to Oracle. Your style creating a class with a connection method, object creation to get connection is excellent.

    Thank you very much Sir.

    God bless you Sir.


  45. manish

    hey every1 cn u hlp me nd suggest a topic for my proj for the subj “INFORMATICS PRACTICES” m in 12th standard ryt nw…!! rply..!

    Thnkx 4 ua concern

  46. Rika

    Thanks for your info! it’s helpfull.
    Anyway may I have this tutorial in a pdf file. Thanks a lot

  47. shalini

    hey m not understanding dis..can u say how to add dat library on netbeans(jdbc driver)..please m new to dis..can u help me

  48. shalini

    hey i got how to connect dis..just wanna know where dis programs ll b stored…like in java software r netbeans software..nd where the exact location

  49. linglom

    Hi, Shalini
    I showed how to add a library on this post on step 2 of this post. A project will be stored on the path that you define when you created it.

  50. shalini

    hi i just wanna know dat dis mysql need some password to access..i have given the password but after somedays i changed the m not able to access the mysql…can u help me please……

  51. lunar

    Hi everyone, when i connect to mysql on Netbeans, it’s successful. But when i build to jar file, and i run :
    java -jar test.jar
    It’s not worked.
    Here is my code :
    String serverName = HeadNodeIp;
    String mydatabase = “hpcosdb”;
    String url = “jdbc:mysql://” + serverName + “/” + mydatabase; // a JDBC url
    String username = “root”;
    String password = “123456”;
    // Load the JDBC driver
    String driverName = “”; // MySQL MM JDBC driver

    System.out.println(“pass class.forName”);
    // Create a connection to the database
    Connection conn = DriverManager.getConnection(url, username, password);

    System.out.println(“pass Connection”);

    Error at :
    DriverManager.getConnection(url, username, password);

    Here is result when i run : java -jar test.jar
    pass class.forName
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘????????????????’ at line 1
    at com.mysql.jdbc.SQLError.createSQLException(
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(
    at com.mysql.jdbc.MysqlIO.sendCommand(
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(
    at com.mysql.jdbc.ConnectionImpl.execSQL(
    at com.mysql.jdbc.ConnectionImpl.configureClientCharacterSet(
    at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(
    at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(
    at com.mysql.jdbc.ConnectionImpl.createNewIO(
    at com.mysql.jdbc.ConnectionImpl.(
    at com.mysql.jdbc.ConnectionImpl.getInstance(
    at com.mysql.jdbc.NonRegisteringDriver.connect(
    at java.sql.DriverManager.getConnection(
    at java.sql.DriverManager.getConnection(
    at test.DBCommunication.ExecuteQuerry(
    at test.Main.main(
    SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘????????????????’ at line 1
    SQLState: 42000
    VendorError: 1064

    Can anybody help me ?

  52. lunar

    Hi, i found the reason. When i installed Netbean, i set it link to jdk 1.6. But, jdk of my debian is the version 1.5. So, when i built to jar file and run , it’s not worked in jdk 1.5.
    I updated jdk to version 1.6 and it’s worked !

  53. subhalaxmi

    i m getting a error below dis line
    s.updateQuery(“insert into introntb (Accessionid,Organism,Defintion) values (‘”+id+”””+org+”””+def+”‘”);
    is dis query writing z correct.
    my db is created in mysql when i want to insert d values dis problem arises

  54. balamurugan

    when I compile your code
    I get following exception
    com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

    I solution friend

  55. balamurugan

    I have also used following code

    String connectionUrl = “jdbc:mysql://localhost:3306/balsdb”;
    Connection con = DriverManager.getConnection(connectionUrl,”Admin”,”admin”);

    but i ‘ve got following exception
    ava.sql.SQLException: Access denied for user ‘Admin’@’localhost’ (using password: YES)
    can u explain what it means friend

  56. linglom

    Hi, Balamurugan

    Verify if that username and password is correct and it has sufficient privilege to access the selected database.

  57. Satya Prakash

    I am new fool in Java world. I started learning JAva and servlet.
    I used mysql using eclipse after installing connector J but the code from netBeans was not working.
    I could not understand why I need to add the file in project lib when I have added that jar file in path.

  58. Dhruv Patel

    Hey friends. Thanks for all this information. I am new in Java programming and this information helps me a lot. Thanks again.

  59. sneha

    my problem is that when i am connecting my to netbeans,there is an occurs in creating ReultSet objects.
    code is showing that ResultSet method is not found,it belongs to java.beans.String.
    I imported java.beans.*; but the problem is not getting solved.

  60. sneha

    because of my problem all options available with ResultSet object such as executequery and executeupdate are not coming which are essential for fetching data from database.
    pls solve my prblm.

  61. beth


    I need help in connecting a database (mysql) to a java web application. Please help by giving me an idea on how to go about it. I don’t have an idea.


  62. Richa

    M a newbie trying to connect existing MySQL sample databases through Netbeans 6.9.1. Connections are OK. It also shows the database (e.g. sakila) on the link:
    jdbc:mysql://localhost:3306/sakila [root on default schema]
    But the problem is that the Tables folder remains empty.
    I have downloaded and re-installed sakila multiple times but problem is not solved. Please help. Thanx.

  63. venkat

    Hi ,
    i tried the above method,but i got

    SQL Exception: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    BUILD SUCCESSFUL (total time: 9 seconds)

    can u please help me in getting through this problem..

  64. Sait

    Thank you very much for this simple and effective tutorial.
    It just works when done step-by-step.
    All clear.

  65. Byron

    Class Not Found Exception: java.lang.ClassNotFoundException: com.mysql.jdbc.driver

    that is my output… need help… am using Netbeans 6.9.1…

    do I still need to download mysql connector.? can’t configure it though… 🙁 pls post or email me 😀 thanks

  66. Harshit

    hey i am using Netbeans Ide 6.5 and can connect mysql database through services but finding problem in program it always shows the Exception statement i.e. Error in Conectivity
    .can anyone help me out.?


    hi thanks for the tutorial it really helped me,i was developing an application and got hooked up,but with your tutorial on mysqljdbc-connector 5.0,wow i feel so relieved thanks very much

  68. linglom

    Hi, Byron

    Have you add MySQL Connector/J library to your project and “import java.sql.*;” in your code?

    Hi, Harshit

    Can you show the full error message?

  69. ASHWIN


    thanks for this information this will definitely helps me a lot.
    please send me about the second part

  70. polaris

    hi sir,
    what does this statement means?

    SQL Exception: java.sql.SQLException: Access denied for user ‘root’@’localhost’ (using password: YES)
    BUILD SUCCESSFUL (total time: 0 seconds)

  71. Raj

    i m create a DB & connect with DB and Connection is i m create a project Java Desktop Application using NetBeans.when i select DB Connection it will show error…
    Connected Database doesn’t containt Tables..

    plz help

  72. linglom

    Hi, Polaris
    Most likely, you did not set credentials for your MySQL server. By default, root account does not require a password when connecting from localhost.
    You can either create a new account with a password and use that account instead root or set new password for root account.

    Hi, Raj
    Never seen this problem myself. Have you verify that your database that you’re connecting to has some table?

  73. black300

    hi all ,
    im trying to develop a small desktop database application so in my final step i wanted to set a code that give me the ability to import data from an excel file to my Mysql DB using Java so
    i downloaded the jexcelapi and load it into my lib and then i set this code :

    —– 1st class named :———
    package javaapplication13;

    * @author DJO
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;

    public class DBConnection {
    public Connection con;
    public static void main(String args[]) {
    Connection con =null;

    try {
    Class.forName(“com.mysql.jdbc.Driver”).newInstance ();
    con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/DJO”,”root”,”root”);

    } catch(Exception exe) {
    System.err.println(“Exception: ” + exe.getMessage());
    } finally {
    try {
    if(con != null)
    } catch(SQLException exe) {System.out.println(“fof ” + exe);}

    2scnd class :

    import jxl.*;
    import javax.swing.*;
    import java.awt.*;
    import java.sql.*;
    import java.awt.event.*;
    import java.util.*;
    public class ExToMy extends JFrame implements ActionListener{
    /*swing components*/
    private JLabel l_xlfile,l_xlsheets,l_mytables;
    private JTextField xlfile;
    private JComboBox xlsheets,mytables;
    private JButton browse,convert,reload_file;
    private JFileChooser filechoose;
    private GridBagLayout gbl;
    private GridBagConstraints gbc;
    /*swing components*/
    java.util.List my_fields_type;
    DBConnection db;
    Statement stat;
    ResultSet rs;
    Workbook workbook;
    private String[] sheet_names;
    public ExToMy(){
    db=new DBConnection();
    catch(Exception exe){}
    /*Layout settings*/
    gbl=new GridBagLayout();
    gbc=new GridBagConstraints();
    setTitle(“Excel to mysql Converter”);
    /*Layout settings*/
    public void initComponents(){
    l_xlfile=new JLabel(“Select a ms excel file to open”);
    l_xlsheets=new JLabel(“Worksheets in workbook”);
    l_mytables=new JLabel(“MySQL tables”);
    xlfile=new JTextField();
    xlsheets=new JComboBox();
    mytables=new JComboBox();
    browse=new JButton(“Browse”);
    reload_file=new JButton(“Reload File”);
    convert=new JButton(“Convert”);
    filechoose=new JFileChooser();
    my_fields_type=new ArrayList();
    public void initDB(){
    rs=stat.executeQuery(“SHOW TABLES”);
    catch(Exception exe){System.out.println(“”+exe);}
    public void posComponent(Component comp,GridBagLayout gbl,GridBagConstraints
    gbc,int posx,int posy){
    public void openXls(){
    int val=filechoose.showOpenDialog(this);
    if(val == JFileChooser.APPROVE_OPTION) {
    Workbook.getWorkbook(filechoose.getSelectedFile()) ;
    xlfile.setText(filechoose.getSelectedFile().getPat h());
    sheet_names=workbook.getSheetNames(); //A stringarray of sheet names is returned
    for(int i=0;i<sheet_names.length;i++){
    exe){JOptionPane.showMessageDialog(this,(String)"S elect a valid excel(.xls)file");}
    public void actionPerformed(ActionEvent ev){
    Object source=ev.getSource();
    Workbook.getWorkbook(filechoose.getSelectedFile()) ;
    sheet_names=workbook.getSheetNames(); //A string array ofsheet names is returned
    for(int i=0;i<sheet_names.length;i++){
    catch(Exception exe){}
    JOptionPane.showMessageDialog(this,(String)"Select a validexcel(.xls) file to select a worksheet");
    int xl_fields=0,my_fields=0,xl_row_count=0;
    String insert_query="";
    sheet=workbook.getSheet(xlsheets.getSelectedIndex( ));
    //JOptionPane.showMessageDialog(this,(String)"Number of Fields are equal");
    for(int j=0;j<xl_row_count;j++){
    insert_query="INSERT INTO"+sel_table_name+" VALUES(";
    for(int i=0;i=0||field_type.indexO f(“float”)>=0||
    insert_query+=sheet.getCell(i,j).getContents().toS tring()+”,”;
    insert_query+=”\'”+sheet.getCell(i,j).getContents( )+”\’,”;
    insert_query=insert_query.substring(0,insert_query .length()-1)+”)”;
    exe){JOptionPane.showMessageDialog(this,(String)”R ow No “+j+””+exe);System.out.println(“”+exe);}
    JOptionPane.showMessageDialog(this,(String)”All rows Successfully copied”);
    JOptionPane.showMessageDialog(this,(String)”Number of Fields are notequal”);
    JOptionPane.showMessageDialog(this,(String)”Select same worksheet name asmysql table”);
    catch(Exception exe){System.out.println(“”+exe);}
    public static void main(String[] args){
    ExToMy exm=new ExToMy();


    the problem now is when i run ExToMy class it runs with success and im able to choose my excel file but i m not able to see the tables in the JLabel MySQL tables” , it’s empty and i have more than 3 tables but nothing is shown ;
    so please if anyone found the error or have the solution i will be so much thankful !

  74. Biju Medayil

    I got the communication link failure error when i connect to my Linux,MySql environment,at last i found the problem.I disabled the Firewall from Firewall configuration. now its working fine.

  75. alberto

    thanks a lot 4 this guide, i solved the problem i had with nullPointerException generated by Class.forName(“com.mysql.jdbc.Driver”) . I missed the jar connector file in my project!

  76. javaman

    help me..

    i have

    i want to open my jar file in another computer. how do i do it? should i change the localhost to my ip address? help pleasee

  77. Bob

    I am running NetBeans 7.0 on Windows 7 and am trying to use a servlet to access a MySQL database. I have followed your instructions for the driver installation (mysql-connector-java-5.1.18-bin.jar) and that all seemed to work correctly. But now NetBeans say there are 10 different files in the driver software that have syntax errors. For example, in CallableStatement.Java in the first directory.
    What did I do wrong?

  78. amzela

    hi there, i managed to connect to database using the above code. looking forward to part 2. i am designing a help desk system using netbeans and mySQL

  79. Willy

    Hi I have been trying to connect to mySQL database for a long time in vain but today i tried this magnificent and simple code and it worked. Thanks alot and may God bless.

  80. Todd

    Regarding the Class.forname()… It should be noted from the Java docs.. “Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)”

  81. yashaarya

    How to install JDBCMysqlDriver Library on Ubuntu. i tried following the way it is done in windows but nothing is happening. i use Mysql through the terminal of Ubuntu. is that the problem? could you please tell me how to resolve this bcoz i really need it to complete my school project due next week.

  82. Gaurav

    Unknown database ‘thread.sql’
    I am using mysql file thread.sql in directory of project folder itself. and statement like this,
    “jdbc:mysql://localhost/thread.sql?” but it gives above error..

  83. mike

    SQL Exception: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    BUILD SUCCESSFUL (total time: 9 seconds)

    hello everyone, can you please help me determine what’s wrong.i follow the instructions, then when i run the code that is the output.

  84. jakoyoski

    am developing a web based eshop on JEE platform. my application can not connect to the database the following is the code am using to connect

    package org.grb.controller;

    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;

    public class loginServlet extends HttpServlet {
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException {
    String username=req.getParameter(“username”);
    String password=req.getParameter(“password”);

    PrintWriter out = res.getWriter();
    try {
    Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/e_shop”,””,””);
    Statement stmt=con.createStatement();
    String sql=(“insert into loginTable(username,password) values(‘username’,’password’)”);
    out.println(“Message successfully added!”);
    catch(Exception e){

  85. biju medayil

    Change the first line in try Block To

    Also check the mysql connector jar file in your Class Path

  86. deep

    as per step 3 i clicked to the button add jar file but it cant open the new window so i can add the jar file…..

  87. mohan

    I have an error like this please help me……..
    “Class Not Found Exception: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver”………….

  88. ammouna

    i have a big problem can someone help me please,
    i’m using netbeans7.1 and mysql5.5 i want to connect the BD with the interface jframe.but i always have this exception:
    “SQL Exception: java.sql.SQLException: Access denied for user ‘root’@’localhost’ (using password: YES)”

    also i created 4 jframe in the same package when i click the button in the first one the second must show up but it doesn’ what i must do???please help me because this application is for the stage!!!!

  89. Manas

    Write a java program that will provide the functionality. When the program starts, it should ask Transaction size as input (it will be tested with max value of 5). After entering the value of transaction size, A menu providing following options should be displayed
    a. Display all records
    b. inserting records
    get the data from stdin
    record will contain USN, Name, address, phone, date of birth
    c. deleting records
    get the USN and delete the records
    d. Display individual records
    get the ISN and display the record
    f. Exit
    If number of operations less than as input in a), then commit
    Anytime number of operations exceeds the transaction size as asked in the beginning, commit then and continue.
    . At exit, commit the transaction even if number of operations carried as per menu is less than the transaction size chosen at the start.
    . If working in team, ensure that both the USN numbers are mentioned as the comment in java code. Ideally, it would be better to run the program from one account, and use DB of other USN.
    . No fancy GUI required. Simple standard console input/output would work.
    . The DB table should have primary key on USN, and other fields should at least include
    – name (alphanumeric)
    – address (alphanumeric)
    – date of birth (as a Date field)
    – phone (as a numeric field)

    Plz help me out !!

  90. jen


    I am completely new to netbeans and mysql database.I have done all this still it is not working. Do i have to do ODBC jdbc CONNECTION in ctrl panel? and SHOULD I start mysql server? If so how to do it?

  91. MuthuAnanth

    I am trying to connect MySQL5.1 in Netbeans7.0.1 RC1 build in Windows 7.

    But there connection refused error has been occured.

    In Services –> Database –> RegisterMySQLServer i have given this details.

    Basic Prop

    HostName : localhost port : 3306 uname : root pwd : root

    admin prop

    Path/url admin tool : C:\Program Files\MySQL\MySQL Server 5.1\bin\mysql.exe

    arg :

    Path to start cmd : C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld.exe

    arg :

    path to stop cmd : C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqladmin.exe

    arg : -u root -proot stop

    But connection refused error is coming. I checked jar file placed in correct place. And using mysql-connector-java-5.1.13-bin.jar.

    Anybody knows solution, kindly help me

    M.Muthu Ananth Haiahtum Software

  92. Manash JK

    I am making a project on payroll management system ,myself, for college project..
    i am facing a problem..
    the method
    Does n’t work(when i type it show error) in NetBeans IDE 6:5:1 verson..
    in when i click login button it open but i want to close login when welcome open..

    Can any one help me?? For database m using MySQl,…

  93. priya

    I have a problem during connection to jdbc. it is showing this–java.sql.SQLException: No suitable driver found for mysql://localhost:3306/company. I am totaly confused what to do.
    I have NetBeans- 7.3.1;
    MySql- Xampp 3.2.1;

    Please reply.

  94. linglom

    Hi Priya,

    Can you post your code snippet (the connection part)? This error message could be that the JDBC driver is loaded properly, or the JDBC URL is wrong. Try to add this code before the connection.

    If it doesn’t help, try the recent version of the MySQL connector,

  95. Elie samyoun


    i wrote the code below and everything went normal !
    the database was connected successfully but i’m having this error
    SQL Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user

    please any kind of help ? almost don’t know what to do
    it’s a college project

  96. linglom


    The error message tells that the user that you’re using doesn’t has permission to access database. Make sure that you have grant permission for the user on MySQL server. See this post as example.

  97. Eddie

    Hello all. I am completely new to netbeans but I am developing an school management systen APP that can get strings from the user and then send it to the database but my challenge now is how can I retrieve from the database and which of the tools in the netbeans can I use to load passport into the registration form

  98. Eddie

    A special thanks to you guys to post I made on the 17th June. I could connect to the database but the picture (passport is not displaying only the name of the passport is displaying in the form). Please anyone help on how go about this.

  99. rencontre infidèle

    With havin so much written content do you ever run into any problems of plagorism or copyright
    infringement? My blog has a lot of completely unique content I’ve either created myaelf or
    outsourced but it looks like a lot off it
    is popping it up all over the internet without my authorization. Do you
    know any techniques to hekp protect against content from being ripped off?
    I’d definitely appreciate it.

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *