Wednesday 21 March 2012

Using MySQL server in java netbeans 6.8

I found many codes to connect with MySQL Server i tried that ones, but fails to connect.  after a long effort i found that you just need to add the MySQL JDBC Drivers to your project libraries.
right click on libraries folder in your project and click on add library. you will see a list of libraries just select the required labray and click on add. the simply use this code.


          Connection conn = null;

           try
           {
               String url = "jdbc:mysql://localhost/";
               Class.forName ("com.mysql.jdbc.Driver").newInstance ();
               conn = 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 */ }
               }
           }

No comments:

Post a Comment