
Tạo java project
Ở eclipse, bạn làm như sau: File -> Other... -> Java Project, sau đó Next như hình bên dưới.
Hộp thoại mới hiện ra, ở đây bạn cần cung cấp một số thông tin về project. Trong ví dụ này mình đặt tên project là DbDemo. Làm như hình nhé, nhập tên cho project xong thì chọn Finish.
Done! Thế là bạn đã tạo ra được một java project rồi. Dĩ nhiên là project vẩn chưa có gì cả, trống không như hình bên dưới.
Thêm thư viện
Đầu tiên bạn tạo một folder trong project tên là lib như sau: Click chuột phải vào DbDemo -> New -> Folder.
Hộp thoại xuất hiện, bạn nhập tên folder là lib như hình dưới và chọn finish.
Cài folder lib này sẽ dùng để chứa các thư viện jar mà bạn add vô project. Hừm! thế thư viện gì và đào đâu ra? Mà dùng nó để làm cái quái gì?
Đây nhé, như bạn đã biết thì ta có cả tá hệ quản trị csdl và java muốn giao tiếp với tụi nó để làm việc với csdl thì cần phải có "driver". Như kiểu có hàng tá loại card màng hình và Windows muốn giao tiếp với tụi nó thì phải cài driver vậy. Vì thế nên ta cần phải tải thêm thư viện của bên thứ 3 tương ứng với loại csdl mà ta muốn làm việc. Trong bài này mình sẽ demo với SQLite nên để lấy thư viện này thì bạn theo link sau: https://bitbucket.org/xerial/sqlite-jdbc/downloads.
Vào đây thì bạn sẽ hơi bị hoang mang vì có cả tá version, biết tải cái nào chừ
Đừng lo, cứ cắm đầu tải cái nào mới nhất, version to nhất ấy.

Như trong hình thì là 3.8.12.2, click vào để tải ẻm nó về máy. Sau khi tải về bạn kéo thả nó vào folder lib lúc nảy vừa tạo ấy.
Bước cuối cùng để có thể sử dụng được thư viện jar đó là cần add nó vào build path của project, bạn làm như sau: Click chuột phải vào file jar trong folder lib -> Build Path -> Add to Build Path.
Coding
Toát hết mồ hồi, cuối cùng cũng được code rồi
Để làm việc với csdl thì có 4 bước cơ bản mà bạn nên tuân theo như sau:

- Load driver.
- Tạo kết nối.
- Truy vấn.
- Đóng kết nối.
Bước 1: Để load driver bạn có thể sử dụng phương thức Class.forName như sau.
Class.forName("org.sqlite.JDBC");
Bước 2: Để tạo một kết nối bạn làm như sau.
connection = DriverManager.getConnection(connectionString);
Bước 3: Bạn sẽ sử insert, select, update và delete. 4 công việc cơ bản nhất mà bạn có thể làm, mình sẽ nói cụ thể trong các phần bên dưới đây.
Bước 4: Đóng kết nối bạn làm như sau.
Bước 4: Đóng kết nối bạn làm như sau.
connection.close();
Insert
Bạn sử dụng câu lệnh insert khi cần thêm thông tin vào một bảng trong csdl. Bạn tạo mới một class tên là InsertSample với một hàm main như sau:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogspot.sontx.tut.dbdemo; | |
public class InsertSample { | |
public static void main(String[] args) { | |
} | |
} |
Code thêm vài dòng như thế này nữa nhé
mình chú thích rất đầy đủ rồi nên có lẻ cũng không cần giải thích gì nhiều.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogspot.sontx.tut.dbdemo; | |
import java.sql.*; | |
public class InsertSample { | |
public static void main(String[] args) throws ClassNotFoundException { | |
// step 1: load driver | |
Class.forName("org.sqlite.JDBC"); | |
Connection connection = null; | |
try { | |
// step 2: create a database connection | |
connection = DriverManager.getConnection("jdbc:sqlite:sample.db"); | |
// step 3: work with your database | |
Statement statement = connection.createStatement(); | |
// if table exists, remove it | |
statement.executeUpdate("drop table if exists person"); | |
// and then, create a new one. A table with two columns are id and name | |
statement.executeUpdate("create table person (id integer, name string)"); | |
// finally, we will insert three persons to this table | |
statement.executeUpdate("insert into person values(1, 'tran xuan son')"); | |
statement.executeUpdate("insert into person values(2, 'tran xuan soan')"); | |
statement.executeUpdate("insert into person values(2, 'tran xuan xon')"); | |
} catch (SQLException e) { | |
} finally { | |
try { | |
if (connection != null) | |
connection.close(); | |
} catch (SQLException e) { | |
// step 4: close connection | |
System.err.println(e); | |
} | |
} | |
} | |
} | |
Select
Câu lệnh select được sử dụng để lấy về các bản ghi(hoặc các dòng) trong một hoặc nhiều bảng. Bạn tạo một class SelectSample và code như bên dưới.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogspot.sontx.tut.dbdemo; | |
import java.sql.*; | |
public class SelectSample { | |
public static void main(String[] args) throws ClassNotFoundException { | |
// step 1: load driver | |
Class.forName("org.sqlite.JDBC"); | |
Connection connection = null; | |
try { | |
// step 2: create a database connection | |
connection = DriverManager.getConnection("jdbc:sqlite:sample.db"); | |
// step 3: work with your database | |
Statement statement = connection.createStatement(); | |
// select all persons in table | |
ResultSet rs = statement.executeQuery("select * from person"); | |
// and then show it | |
while (rs.next()) { | |
System.out.println("name = " + rs.getString("name")); | |
System.out.println("id = " + rs.getInt("id")); | |
} | |
} catch (SQLException e) { | |
} finally { | |
try { | |
if (connection != null) | |
connection.close(); | |
} catch (SQLException e) { | |
// step 4: close connection | |
System.err.println(e); | |
} | |
} | |
} | |
} |
Đây là kết quả sau khi chạy đoạn lệnh trên, tất cả các bảng ghi trong table đều được "show" ra hết ở đây 

Update
Bạn dùng nó khi bạn cần chỉnh sửa nội dung một hay nhiều bản ghi trong bảng. Ví dụ như cần đổi tên của người có ID là 001 thành "trần xuân soạn chẳng hạn". Tạo một class UpdateSample và code như sau.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogspot.sontx.tut.dbdemo; | |
import java.sql.*; | |
public class UpdateSample { | |
public static void main(String[] args) throws ClassNotFoundException { | |
// step 1: load driver | |
Class.forName("org.sqlite.JDBC"); | |
Connection connection = null; | |
try { | |
// step 2: create a database connection | |
connection = DriverManager.getConnection("jdbc:sqlite:sample.db"); | |
// step 3: work with your database | |
Statement statement = connection.createStatement(); | |
// rename person who has id is 1 to "tran xuan soan" | |
statement.executeUpdate("update person set name='tran xuan soan' where id=1"); | |
} catch (SQLException e) { | |
} finally { | |
try { | |
if (connection != null) | |
connection.close(); | |
} catch (SQLException e) { | |
// step 4: close connection | |
System.err.println(e); | |
} | |
} | |
} | |
} |
Bạn thử chạy đoạn lệnh này sau đó chạy lại đoạn lệnh của select bên trên sẽ thấy rỏ tên của người có id 1 đã bị đổi thành "tran xuan soan".
Delete
Đôi lúc bạn cần xóa một số bản ghi trong table, ví dụ như xóa những người có chữ |"soan" trong tên chẳng hạn. Làm như sau nhé, tạo class DeleteSample.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogspot.sontx.tut.dbdemo; | |
import java.sql.*; | |
public class DeleteSample { | |
public static void main(String[] args) throws ClassNotFoundException { | |
// step 1: load driver | |
Class.forName("org.sqlite.JDBC"); | |
Connection connection = null; | |
try { | |
// step 2: create a database connection | |
connection = DriverManager.getConnection("jdbc:sqlite:sample.db"); | |
// step 3: work with your database | |
Statement statement = connection.createStatement(); | |
// rename person who has id is 1 to "tran xuan soan" | |
statement.executeUpdate("delete from person where name like '%soan%'"); | |
} catch (SQLException e) { | |
} finally { | |
try { | |
if (connection != null) | |
connection.close(); | |
} catch (SQLException e) { | |
// step 4: close connection | |
System.err.println(e); | |
} | |
} | |
} | |
} |
Sau khi chạy đoạn lệnh trên bạn chạy lại đoạn lệnh của select để xem kết quả.
Hai người đầu tiên có chữ "soan" ở trong tên đã bị remove rồi 
Trước |
Sau |

Chốt
Việc lựa chọn hệ quản trị csdl nào là tùy thuộc vào tùng trường hợp, khi bạn cần triển khai những hệ thống lớn, yêu cầu bảo mật blabla các kiểu thì lúc này MySQL hay SQLServer... là một sự lựa chọn hợp lý. Đôi lúc bạn chỉ muốn lưu trữ những thông tin đơn giản như thông tin của game hay của ứng dụng thì SQLite là OK nhất. Ngay chính Firefox hay Chrome cũng đang dùng SQLite để lưu trữ lịch sử trình duyệt cùng các thông tin khác đấy 

Đây là source code cho bài viết hôm nay: https://github.com/sontx/db-demo
0 nhận xét :
Post a Comment