Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i have just installed mysql server 5 and NetBeans 7.1

i want to know how to use java to connect to database on mysql server

it is a code i found on net

Java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database_con;
import java.sql.*;
/**
 *
 * @author engamir
 */
public class Database_con {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println("MySQL Connect Example.");
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "test";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root"; 
        String password = "globalamirtarek";
        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url+dbName,userName,password);
            System.out.println("Connected to the database");
            conn.close();
            System.out.println("Disconnected from database");
        } 
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) 
        {
            System.out.println(e.getMessage());
        }
    }
}


this code enter the catch with ClassNotFoundException

i can find this Driver under Drivers list under services on Netbeans and i can connect using it to the mysql database

can any one tell me if i make something wrong?
Posted
Updated 4-Jul-12 2:45am
v2

1 solution

looks good spontaneous.

When you get a ClassNotFound Exception - which class is not found?

Please make sure that all parts are in the build:

Configuring the build in Netbeans[^]
 
Share this answer
 
Comments
amir tarek 5-Jul-12 5:59am    
this is the class of the driver

i solved it

i added the jar file of com.mysql.jdbc.Driver to the libraries of the project and it works

thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900