Để kết nối ứng dụng Java với cơ sở dữ liệu MySQL, chúng tôi cần làm theo 5 bước sau.
Trong ví dụ này, chúng tôi đang sử dụng MySQL làm cơ sở dữ liệu. Vì vậy, chúng ta cần biết thông tin sau cho cơ sở dữ liệu MySQL:
- Lớp trình điều khiển: Lớp trình điều khiển cho cơ sở dữ liệu MySQL là com.mysql.jdbc.driver. The driver class for the mysql database is com.mysql.jdbc.Driver.
- URL kết nối: URL kết nối cho cơ sở dữ liệu MySQL là JDBC: MySQL: // LocalHost: 3306/Sonoo trong đó JDBC là API, MySQL là cơ sở dữ liệu, LocalHost là tên máy chủ mà MySQL đang chạy, chúng tôi cũng có thể sử dụng địa chỉ IP IP , 3306 là số cổng và Sonoo là tên cơ sở dữ liệu. Chúng tôi có thể sử dụng bất kỳ cơ sở dữ liệu nào, trong trường hợp như vậy, chúng tôi cần thay thế Sonoo bằng tên cơ sở dữ liệu của chúng tôi. The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name. We may use any database, in such case, we need to replace the sonoo with our database name.
- Tên người dùng: Tên người dùng mặc định cho cơ sở dữ liệu MySQL là root. The default username for the mysql database is root.
- Mật khẩu: Đó là mật khẩu được cung cấp bởi người dùng tại thời điểm cài đặt cơ sở dữ liệu MySQL. Trong ví dụ này, chúng tôi sẽ sử dụng Root làm mật khẩu. It is the password given by the user at the time of installing the mysql database. In this example, we are going to use root as the password.
Trước tiên chúng ta hãy tạo một bảng trong cơ sở dữ liệu MySQL, nhưng trước khi tạo bảng, chúng ta cần tạo cơ sở dữ liệu trước.
Ví dụ để kết nối ứng dụng Java với cơ sở dữ liệu MySQL
Trong ví dụ này, Sonoo là tên cơ sở dữ liệu, root là tên người dùng và mật khẩu cả hai.
Ví dụ trên sẽ lấy tất cả các hồ sơ của bảng EMP.
Để kết nối ứng dụng Java với cơ sở dữ liệu MySQL, tệp mysqlconnector.jar được yêu cầu phải tải.mysqlconnector.jar file is required to be loaded.
Hai cách để tải tệp JAR:
- Dán tệp mysqlconnector.jar trong thư mục JRE/LIB/EXT
- Đặt ClassPath
1] Dán tệp mysqlconnector.jar vào thư mục JRE/LIB/EXT:
Tải xuống tệp mysqlconnector.jar. Chuyển đến thư mục JRE/LIB/EXT và dán tệp JAR ở đây.
2] Đặt ClassPath:
Có hai cách để đặt đường dẫn lớp:
- tạm thời
- dài hạn
Cách đặt đường dẫn đẳng cấp tạm thời
Mở dấu nhắc lệnh và viết:
Cách đặt đường dẫn lớp vĩnh viễn
Chuyển đến biến môi trường sau đó nhấp vào tab mới. Trong tên biến viết ClassPath và trong giá trị biến, dán đường dẫn đến tệp mysqlconnector.jar bằng cách nối thêm mysqlconnector.jar;.; như C: \ thư mục \ mysql-connector-java-5.0.8-bin.jar;.;classpath and in variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;
Khởi tạo hằng số cơ sở dữ liệu
Tạo các thuộc tính không đổi Cơ sở dữ liệu Tên người dùng, Mật khẩu, URL và Trình điều khiển, Giới hạn bỏ phiếu, v.v.
// init database constants
// com.mysql.jdbc.Driver
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250"; // set your own limit
Khởi tạo kết nối và thuộc tính
Khi kết nối được thiết lập, tốt hơn là lưu trữ cho mục đích tái sử dụng.
// init connection object
private Connection connection;
// init properties object
private Properties properties;
Tạo thuộc tính
Đối tượng thuộc tính giữ thông tin kết nối, kiểm tra xem nó đã được đặt.
// create properties
private Properties getProperties[] {
if [properties == null] {
properties = new Properties[];
properties.setProperty["user", USERNAME];
properties.setProperty["password", PASSWORD];
properties.setProperty["MaxPooledStatements", MAX_POOL];
}
return properties;
}
Kết nối cơ sở dữ liệu
Bây giờ kết nối với cơ sở dữ liệu bằng cách sử dụng các hằng số và thuộc tính được khởi tạo.
// connect database
public Connection connect[] {
if [connection == null] {
try {
Class.forName[DATABASE_DRIVER];
connection = DriverManager.getConnection[DATABASE_URL, getProperties[]];
} catch [ClassNotFoundException | SQLException e] {
// Java 7+
e.printStackTrace[];
}
}
return connection;
}
Ngắt kết nối cơ sở dữ liệu
Khi bạn đã hoàn thành các hoạt động cơ sở dữ liệu, chỉ cần đóng kết nối.
// disconnect database
public void disconnect[] {
if [connection != null] {
try {
connection.close[];
connection = null;
} catch [SQLException e] {
e.printStackTrace[];
}
}
}
Mọi thứ cùng nhau
Sử dụng lớp này MysqlConnect
trực tiếp sau khi thay đổi cơ sở dữ liệu_name, tên người dùng và mật khẩu, v.v.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MysqlConnect {
// init database constants
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250";
// init connection object
private Connection connection;
// init properties object
private Properties properties;
// create properties
private Properties getProperties[] {
if [properties == null] {
properties = new Properties[];
properties.setProperty["user", USERNAME];
properties.setProperty["password", PASSWORD];
properties.setProperty["MaxPooledStatements", MAX_POOL];
}
return properties;
}
// connect database
public Connection connect[] {
if [connection == null] {
try {
Class.forName[DATABASE_DRIVER];
connection = DriverManager.getConnection[DATABASE_URL, getProperties[]];
} catch [ClassNotFoundException | SQLException e] {
e.printStackTrace[];
}
}
return connection;
}
// disconnect database
public void disconnect[] {
if [connection != null] {
try {
connection.close[];
connection = null;
} catch [SQLException e] {
e.printStackTrace[];
}
}
}
}
Làm thế nào để sử dụng?
Khởi tạo lớp cơ sở dữ liệu.
// !_ note _! this is just init
// it will not create a connection
MysqlConnect mysqlConnect = new MysqlConnect[];
Ở một nơi khác trong mã của bạn ...
String sql = "SELECT * FROM `stackoverflow`";
try {
PreparedStatement statement = mysqlConnect.connect[].prepareStatement[sql];
... go on ...
... go on ...
... DONE ....
} catch [SQLException e] {
e.printStackTrace[];
} finally {
mysqlConnect.disconnect[];
}
Đây là tất cả :] Nếu bất cứ điều gì để cải thiện chỉnh sửa nó! Hy vọng điều này là hữu ích.:] If anything to improve edit it! Hope this is helpful.