Cách kết nối MySQL workbench với netbean

Trong bài này bạn sẽ được học cách kết nối MySQL bằng cách sử dụng thư viện Java JDBC Connection, đây là bước đầu và quan trọng nhất khi bạn muốn xử lý database trong Java JDBC.

Cách kết nối MySQL workbench với netbean

Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Để kết nối với MySQL từ một chương trình Java thì bạn cần thực hiện các bước sau:

  • Load thư viện MySQL Connector/J vào trong dự án của bạn.
  • Tạo một Object mới từ class DriverManager, sau đó là bạn có thể thực hiện kết nối.

1. Load thư viện MySQL Connector/J

Để load thư viện MySQL Connector/J thì bạn thực hiện các bước sau:

Bước 1: Tại Netbeans IDE bạn hãy tạo một project, sau đó click chuột phải và chọn properties từ menu xổ xuống. Như trong hình dưới đây mình đã đặt tên là MySQLJDBC.

Bài viết này được đăng tại [free tuts .net]

Cách kết nối MySQL workbench với netbean

Bước 2: Tai phía bên tay tráibạn hãy chọn vào

Connection conn = null;
try {
    // db parameters
    String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
    String user      = "root";
    String password  = "secret";
	
    // create a connection to the database
    conn = DriverManager.getConnection(url, user, password);
    // more processing here
    // ...	
} catch(SQLException e) {
   System.out.println(e.getMessage());
} finally {
	try{
           if(conn ! null)
             conn.close()
	}catch(SQLException ex){
           System.out.println(ex.getMessage())
	}
}
0, sau đó click vào button
Connection conn = null;
try {
    // db parameters
    String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
    String user      = "root";
    String password  = "secret";
	
    // create a connection to the database
    conn = DriverManager.getConnection(url, user, password);
    // more processing here
    // ...	
} catch(SQLException e) {
   System.out.println(e.getMessage());
} finally {
	try{
           if(conn ! null)
             conn.close()
	}catch(SQLException ex){
           System.out.println(ex.getMessage())
	}
}
1.

Cách kết nối MySQL workbench với netbean

Bước 3: Một hộp thoại xuất hiện, bạn hãy tìm đến thư mục cài đặt MySQL Connector/J mà bạn đã thực hiện ở bài trước.

Cách kết nối MySQL workbench với netbean

Cách kết nối MySQL workbench với netbean

2. Kết nối MySQL bằng Java JDBC Connection

Đầu tiên bạn hãy import ba class quan trọng nhất vào dự án, đó là

Connection conn = null;
try {
    // db parameters
    String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
    String user      = "root";
    String password  = "secret";
	
    // create a connection to the database
    conn = DriverManager.getConnection(url, user, password);
    // more processing here
    // ...	
} catch(SQLException e) {
   System.out.println(e.getMessage());
} finally {
	try{
           if(conn ! null)
             conn.close()
	}catch(SQLException ex){
           System.out.println(ex.getMessage())
	}
}
2, DriverManager, và
Connection conn = null;
try {
    // db parameters
    String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
    String user      = "root";
    String password  = "secret";
	
    // create a connection to the database
    conn = DriverManager.getConnection(url, user, password);
    // more processing here
    // ...	
} catch(SQLException e) {
   System.out.println(e.getMessage());
} finally {
	try{
           if(conn ! null)
             conn.close()
	}catch(SQLException ex){
           System.out.println(ex.getMessage())
	}
}
4 từ
Connection conn = null;
try {
    // db parameters
    String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
    String user      = "root";
    String password  = "secret";
	
    // create a connection to the database
    conn = DriverManager.getConnection(url, user, password);
    // more processing here
    // ...	
} catch(SQLException e) {
   System.out.println(e.getMessage());
} finally {
	try{
           if(conn ! null)
             conn.close()
	}catch(SQLException ex){
           System.out.println(ex.getMessage())
	}
}
5.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

Tiếp theo hãy gọi phương thức

Connection conn = null;
try {
    // db parameters
    String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
    String user      = "root";
    String password  = "secret";
	
    // create a connection to the database
    conn = DriverManager.getConnection(url, user, password);
    // more processing here
    // ...	
} catch(SQLException e) {
   System.out.println(e.getMessage());
} finally {
	try{
           if(conn ! null)
             conn.close()
	}catch(SQLException ex){
           System.out.println(ex.getMessage())
	}
}
6 từ class DriverManager để khởi tạo Connection Object.

Sẽ có ba tham số bạn cần truyền vào phương thức này:

  • url: Đây là chuỗi kết nối database. Đối với MySQL thì nó có dạng như sau
    Connection conn = null;
    try {
        // db parameters
        String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
        String user      = "root";
        String password  = "secret";
    	
        // create a connection to the database
        conn = DriverManager.getConnection(url, user, password);
        // more processing here
        // ...	
    } catch(SQLException e) {
       System.out.println(e.getMessage());
    } finally {
    	try{
               if(conn ! null)
                 conn.close()
    	}catch(SQLException ex){
               System.out.println(ex.getMessage())
    	}
    }
    8, tức là bạn đang kết nối với máy chủ localhost, cổng 3306 và cơ sở dữ liệu tên là
    Connection conn = null;
    try {
        // db parameters
        String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
        String user      = "root";
        String password  = "secret";
    	
        // create a connection to the database
        conn = DriverManager.getConnection(url, user, password);
        // more processing here
        // ...	
    } catch(SQLException e) {
       System.out.println(e.getMessage());
    } finally {
    	try{
               if(conn ! null)
                 conn.close()
    	}catch(SQLException ex){
               System.out.println(ex.getMessage())
    	}
    }
    9.
  • user: Tên đăng nhập của User kết nối vào database
  • password: Mật khẩu của User.

Connection conn = null;
try {
    // db parameters
    String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
    String user      = "root";
    String password  = "secret";
	
    // create a connection to the database
    conn = DriverManager.getConnection(url, user, password);
    // more processing here
    // ...	
} catch(SQLException e) {
   System.out.println(e.getMessage());
} finally {
	try{
           if(conn ! null)
             conn.close()
	}catch(SQLException ex){
           System.out.println(ex.getMessage())
	}
}

Nếu quá trình đăng nhập không thành công bởi một số lý do như: Mật khẩu sai, tên đăng nhập sai, cổng kết nối không tồn tại, database không tồn tại, lúc này sẽ phát sinh ra lỗi SQLException. Vì vậy khi kết nối database bạn nên đặt nó trong khối

// db parameters
String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
String user      = "root";
String password  = "secret";

Connection conn = null;

try(conn = DriverManager.getConnection(url, user, password);) {
	// processing here
} catch(SQLException e) {
   System.out.println(e.getMessage());
}
0 để đảm bảo an toàn.

Ngoài ra sau khi sử dụng xong bạn nên tắt kết nối ngay để tránh bị tấn công vào dữ liệu. Để tắt kết nối khá đơn giản, bạn chỉ cần gọi phương thức close() trong Connection Object mà bạn đã tạo ra.

Từ Java 7 trở lên có một câu lệnh hay khác gọi là

// db parameters
String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
String user      = "root";
String password  = "secret";

Connection conn = null;

try(conn = DriverManager.getConnection(url, user, password);) {
	// processing here
} catch(SQLException e) {
   System.out.println(e.getMessage());
}
1 cho phép bạn đơn giản hóa mã ở trên như sau:

// db parameters
String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
String user      = "root";
String password  = "secret";

Connection conn = null;

try(conn = DriverManager.getConnection(url, user, password);) {
	// processing here
} catch(SQLException e) {
   System.out.println(e.getMessage());
}

Nó tự động gọi phương thức

// db parameters
String url       = "jdbc:mysql://localhost:3306/mysqljdbc";
String user      = "root";
String password  = "secret";

Connection conn = null;

try(conn = DriverManager.getConnection(url, user, password);) {
	// processing here
} catch(SQLException e) {
   System.out.println(e.getMessage());
}
2 của đối tượng Connection sau khi chương trình kết thúc. Như bạn có thể thấy chương trình trở nên rõ ràng hơn nhiều.

Tuy nhiên thực tế bạn không nên sử dụng cách này, bởi nó sẽ gặp một số vấn đề như: Khi bạn đổi database hoặc thông số kết nối thì phải sửa khá nhiều vị trí, đồng thời không được bảo mật khi mã nguôn có quá nhiều nơi kết nối.

Để tránh tạo mã cứng kết nối như vậy thì ta có giải pháp khá hay, đó là tạo ra một file chứa những thông số kết nối này. Lúc nay nếu thay đổi gì thì chỉ cần vào file này thực hiện là được.

Mình tạo một file tên là db.properties với nội dung như sau:

# MySQL DB parameters
user=root
password=secret
url=jdbc:mysql://localhost:3306/mysqljdbc

Để sử dụng nhưng thuộc tính này thì mình sẽ viết lại đoạn code kết nối như sau:

Connection conn = null;

try(FileInputStream f = new FileInputStream("db.properties")) {
    // load the properties file
    Properties pros = new Properties();
    pros.load(f);

    // assign db parameters
    String url       = pros.getProperty("url");
    String user      = pros.getProperty("user");
    String password  = pros.getProperty("password");
    // create a connection to the database
    conn = DriverManager.getConnection(url, user, password);
} catch(IOException e) {
   System.out.println(e.getMessage());
} finally {
    try{
        if(conn != null)
            conn.close();
    }catch(SQLException ex){
        System.out.println(ex.getMessage());
    }
    
}

Với mõi lần tương tác đến MySQL thì bạn sẽ tạo ra một két nối mới, điều này khiến chương trình tốn quá nhiều bộ nhớ để lưu trữ nhưng đối tượng connection đó.

Vì vậy ta nên tạo ra một class riêng và nơi nào muốn sử dụng thì chỉ cần gọi đến là được.

package org.mysqltutorial;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 *
 * @author mysqltutorial.org
 */
public class MySQLJDBCUtil {

    /**
     * Get database connection
     *
     * @return a Connection object
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = null;

        try (FileInputStream f = new FileInputStream("db.properties")) {

            // load the properties file
            Properties pros = new Properties();
            pros.load(f);

            // assign db parameters
            String url = pros.getProperty("url");
            String user = pros.getProperty("user");
            String password = pros.getProperty("password");
            
            // create a connection to the database
            conn = DriverManager.getConnection(url, user, password);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return conn;
    }

}

Như vậy là trong bài này mình đã hướng dẫn xong cách kết nối với MySQL trong Java JDBC Driver. Chúc bạn thực hiện thành công, và gặp lại bạn ở những bài tiếp theo nhé.