Lập Trình Cơ Sở Dữ Liệu Java Swing Cơ Bản – Ôn Tập 6

I. Nhập Cơ Sở Dữ Liệu


--
-- Cơ sở dữ liệu: `mybook`
--

-- --------------------------------------------------------

--
-- Cấu trúc bảng cho bảng `theloai`
--

CREATE TABLE `theloai` (
`MATL` varchar(10) NOT NULL,
`TENTL` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

II. Tạo lớp DBConnection

package laptrinhcsdl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBConnection {

//Đối tượng connect
private Connection conn;
//Đối tượng statement
public Statement stm;

public DBConnection() throws ClassNotFoundException {
try {
//Tải driver
Class.forName("com.mysql.jdbc.Driver");
//Lấy kết nối
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mybook?useUnicode=true&characterEncoding=UTF-8","root","");
stm=conn.createStatement();

} catch (SQLException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

III. Giao diện và sự kiện

Code tham khảo: (có sửa đổi)


package laptrinhcsdl;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.table.DefaultTableModel;

/**
*
* @author USER
*/
public class JFrameTheLoai extends JFrame implements ActionListener {

//Khai bao component
JLabel jlbMATL, jlbTENTL;

JTextField jtxtMATL, jtxtTENTL;

DefaultTableModel model;
JTable jtbTheLoai;

JButton jbtnThem, jbtnXoa, jbtnSua;

JPanel jpnTop, jpnCenter, jpnBottom, jpn1, jpn2;

DBConnection db;

public JFrameTheLoai() throws ClassNotFoundException {
super("LTCSDL");//dat ten
setSize(400, 500);
setLocationRelativeTo(null);//canh giua
setDefaultCloseOperation(EXIT_ON_CLOSE);//tac han chuong trinh
setLayout(new BorderLayout());

db = new DBConnection();

//Khoi tao component
jpnTop = new JPanel(new GridLayout(2, 1));
jpn1 = new JPanel();
jpn2 = new JPanel();
jpnCenter = new JPanel();
jpnBottom = new JPanel();

jlbMATL = new JLabel("MATL");
jlbTENTL = new JLabel("TENTL");

jtxtMATL = new JTextField(20);
jtxtTENTL = new JTextField(20);

jbtnThem = new JButton("Them");
jbtnSua = new JButton("Sua");
jbtnXoa = new JButton("Xoa");

model = new DefaultTableModel();
String[] columnsName = {"MATL", "TENTL"};
model.setColumnIdentifiers(columnsName);

LoadData();
jtbTheLoai = new JTable();
jtbTheLoai.setModel(model);

//Them conponent
jpn1.add(jlbMATL);
jpn1.add(jtxtMATL);

jpn2.add(jlbTENTL);
jpn2.add(jtxtTENTL);

jpnTop.add(jpn1);
jpnTop.add(jpn2);

add(jpnTop, BorderLayout.NORTH);
add(new JScrollPane(jtbTheLoai), BorderLayout.CENTER);
jpnBottom.add(jbtnThem);
jpnBottom.add(jbtnSua);
jpnBottom.add(jbtnXoa);

add(jpnBottom, BorderLayout.SOUTH);

//Thiet lap su kien
jbtnThem.addActionListener(this);
jbtnXoa.addActionListener(this);
jbtnSua.addActionListener(this);

jtbTheLoai.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
jtxtMATL.setText(jtbTheLoai.getValueAt(jtbTheLoai.getSelectedRow(), 0).toString());
jtxtTENTL.setText(jtbTheLoai.getValueAt(jtbTheLoai.getSelectedRow(), 1).toString());
}

});

//Hien thi
setVisible(true);

}

private void LoadData() {
model.setNumRows(0);
try {
String sql = "SELECT * FROM theloai";
ResultSet rs = db.stm.executeQuery(sql);

while (rs.next()) {
String[] row = new String[2];
row[0] = rs.getString("MATL");
row[1] = rs.getString("TENTL");
model.addRow(row);
}

} catch (SQLException ex) {
Logger.getLogger(JFrameTheLoai.class.getName()).log(Level.SEVERE, null, ex);
}
}

public static void main(String[] args) throws ClassNotFoundException {
new JFrameTheLoai();
}

@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == jbtnThem) {
try {
String sql = "INSERT INTO `theloai` (`MATL`, `TENTL`) VALUES ('" + jtxtMATL.getText() + "', '" + jtxtTENTL.getText() + "')";
db.stm.executeUpdate(sql);
LoadData();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex, "Error", JOptionPane.ERROR_MESSAGE);
}
} else if (ae.getSource() == jbtnXoa) {
try {
String sql = "DELETE FROM `theloai` WHERE MATL='" + jtxtMATL.getText() + "'";
db.stm.executeUpdate(sql);
LoadData();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex, "Error", JOptionPane.ERROR_MESSAGE);
}

} else if (ae.getSource() == jbtnSua) {
try {
String matl= model.getValueAt(jtbTheLoai.getSelectedRow(),0).toString();
String sql="UPDATE `theloai` SET `MATL`='"+jtxtMATL.getText()+"',`TENTL`='"+jtxtTENTL.getText()+"' WHERE MATL='"+matl+"'";
db.stm.executeUpdate(sql);
LoadData();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex, "Error", JOptionPane.ERROR_MESSAGE);
}

}
}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s