By GokiSoft.com|
14:54 11/11/2022|
Java Advanced
[Source Code] Tìm hiểu về CSDL - C2109I
B1) Tao CSDL
create table users (
id int primary key auto_increment,
fullname varchar(50),
email varchar(150),
address varchar(200)
)
B2) Tao du an
B3) Add thu vien vao du an
B4) Thao vs CSDL
#Main.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package java2.lesson06;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author diepvan
*/
public class Main {
static List<VeMayBay> veMayBays = new ArrayList<>();
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
//1) Nhập vào thông tin cho n chuyến bay với mã chuyến bay theo quy ước ở trên
// input();
//2. Lưu thông tin vừa nhập vào file : DuLieuBay.txt
// saveFile();
//3. Đọc thông tin từ DuLieuBay.txt và hiển thị tất cả thông tin ra màn hình
readFile();
//4. Hien thi
display();
splitFile();
}
static void splitFile() {
for (VeMayBay veMayBay : veMayBays) {
appendFile(veMayBay.getFileName(), veMayBay);
}
System.out.println("Luu hoan thanh!!!");
}
static void display() {
Collections.sort(veMayBays, (o1, o2) -> {
if(o1.getPrice() < o2.getPrice()) {
return 1;
}
return -1;
});
for (VeMayBay veMayBay : veMayBays) {
veMayBay.display();
}
}
static void readFile() {
FileReader reader = null;
BufferedReader bufferedReader = null;
try {
reader = new FileReader("vmb.txt");
bufferedReader = new BufferedReader(reader);
String line;
while((line = bufferedReader.readLine()) != null) {
if(line.trim().isEmpty()) continue;
VeMayBay vmb = new VeMayBay();
vmb.parseLine(line);
veMayBays.add(vmb);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(reader != null) {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void appendFile(String filename, VeMayBay vmb) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(vmb.getFileName(), true);
byte[] data = vmb.toString().getBytes("utf8");
fos.write(data);
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void saveFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("vmb.txt");
for (VeMayBay veMayBay : veMayBays) {
byte[] data = veMayBay.toString().getBytes("utf8");
fos.write(data);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
static void input() {
System.out.println("Nhap so ve can them: ");
int n = Integer.parseInt(scan.nextLine());
for (int i = 0; i < n; i++) {
VeMayBay veMayBay = new VeMayBay();
veMayBay.input();
veMayBays.add(veMayBay);
}
}
}
#MainFrame.form
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.5" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<Properties>
<Property name="defaultCloseOperation" type="int" value="3"/>
<Property name="title" type="java.lang.String" value="QUAN LY THONG TIN SINH VIEN"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
<SyntheticProperty name="generateCenter" type="boolean" value="false"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jPanel1" max="32767" attributes="0"/>
<Component id="jScrollPane1" max="32767" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel1" min="-2" max="-2" attributes="0"/>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="jScrollPane1" min="-2" pref="232" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
<TitledBorder title="NHAP THONG TIN"/>
</Border>
</Property>
</Properties>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="39" max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" max="-2" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Component id="jLabel2" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
<Component id="txtEmail" min="-2" pref="479" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="1" attributes="0">
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="96" max="-2" attributes="0"/>
<Component id="txtFullname" min="-2" pref="479" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="1" attributes="0">
<Component id="jLabel3" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<Component id="btnSave" min="-2" max="-2" attributes="0"/>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="btnReset" min="-2" max="-2" attributes="0"/>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="btnDelete" min="-2" max="-2" attributes="0"/>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="btnLoadData" min="-2" max="-2" attributes="0"/>
</Group>
<Component id="txtAddress" min="-2" pref="479" max="-2" attributes="0"/>
</Group>
</Group>
</Group>
<EmptySpace pref="66" max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="22" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtFullname" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtEmail" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtAddress" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="btnSave" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnReset" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnDelete" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnLoadData" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace pref="18" max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="jLabel1">
<Properties>
<Property name="text" type="java.lang.String" value="HO TEN:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtFullname">
</Component>
<Component class="javax.swing.JLabel" name="jLabel2">
<Properties>
<Property name="text" type="java.lang.String" value="EMAIL:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtEmail">
</Component>
<Component class="javax.swing.JLabel" name="jLabel3">
<Properties>
<Property name="text" type="java.lang.String" value="DIA CHI:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtAddress">
</Component>
<Component class="javax.swing.JButton" name="btnSave">
<Properties>
<Property name="text" type="java.lang.String" value="SAVE"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnSaveActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnReset">
<Properties>
<Property name="text" type="java.lang.String" value="RESET FORM"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnResetActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnDelete">
<Properties>
<Property name="text" type="java.lang.String" value="DELETE"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnDeleteActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnLoadData">
<Properties>
<Property name="text" type="java.lang.String" value="LOAD DATA"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnLoadDataActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JScrollPane" name="jScrollPane1">
<AuxValues>
<AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="javax.swing.JTable" name="tblStudent">
<Properties>
<Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
<Table columnCount="4" rowCount="0">
<Column editable="false" title="STT" type="java.lang.Object"/>
<Column editable="false" title="HO TEN" type="java.lang.Object"/>
<Column editable="false" title="EMAIL" type="java.lang.Object"/>
<Column editable="false" title="DIA CHI" type="java.lang.Object"/>
</Table>
</Property>
<Property name="columnModel" type="javax.swing.table.TableColumnModel" editor="org.netbeans.modules.form.editors2.TableColumnModelEditor">
<TableColumnModel selectionModel="0">
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
<Title/>
<Editor/>
<Renderer/>
</Column>
</TableColumnModel>
</Property>
<Property name="tableHeader" type="javax.swing.table.JTableHeader" editor="org.netbeans.modules.form.editors2.JTableHeaderEditor">
<TableHeader reorderingAllowed="true" resizingAllowed="true"/>
</Property>
</Properties>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Form>
#MainFrame.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package java2.lesson06;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author diepvan
*/
public class MainFrame extends javax.swing.JFrame {
DefaultTableModel tableModel;
List<Student> dataList = new ArrayList<>();
int currentIndex = -1;
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
tableModel = (DefaultTableModel) tblStudent.getModel();
tblStudent.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
currentIndex = tblStudent.getSelectedRow();
Student std = dataList.get(tblStudent.getSelectedRow());
txtFullname.setText(std.getFullname());
txtEmail.setText(std.getEmail());
txtAddress.setText(std.getAddress());
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtFullname = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtEmail = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtAddress = new javax.swing.JTextField();
btnSave = new javax.swing.JButton();
btnReset = new javax.swing.JButton();
btnDelete = new javax.swing.JButton();
btnLoadData = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblStudent = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("QUAN LY THONG TIN SINH VIEN");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("NHAP THONG TIN"));
jLabel1.setText("HO TEN:");
jLabel2.setText("EMAIL:");
jLabel3.setText("DIA CHI:");
btnSave.setText("SAVE");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnReset.setText("RESET FORM");
btnReset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnResetActionPerformed(evt);
}
});
btnDelete.setText("DELETE");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
btnLoadData.setText("LOAD DATA");
btnLoadData.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadDataActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(96, 96, 96)
.addComponent(txtFullname, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnSave)
.addGap(18, 18, 18)
.addComponent(btnReset)
.addGap(18, 18, 18)
.addComponent(btnDelete)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnLoadData))
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(66, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtFullname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSave)
.addComponent(btnReset)
.addComponent(btnDelete)
.addComponent(btnLoadData))
.addContainerGap(18, Short.MAX_VALUE))
);
tblStudent.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"STT", "HO TEN", "EMAIL", "DIA CHI"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tblStudent);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
// TODO add your handling code here:
System.out.println("Save click...");
String fullname = txtFullname.getText().toString();
String address = txtAddress.getText().toString();
String email = txtEmail.getText().toString();
System.out.println(fullname + ", " + address + ", " + email);
if (currentIndex >= 0) {
dataList.get(currentIndex).setFullname(fullname);
dataList.get(currentIndex).setEmail(email);
dataList.get(currentIndex).setAddress(address);
StudentDAO.update(dataList.get(currentIndex));
} else {
Student std = new Student(fullname, email, address);
//Insert Data -> database
StudentDAO.insert(std);
dataList = StudentDAO.list();
}
showData();
// dataList.add(std);
//
// tableModel.addRow(new Object[] {
// tableModel.getRowCount() + 1,
// fullname,
// email,
// address
// });
}//GEN-LAST:event_btnSaveActionPerformed
void showData() {
tableModel.setRowCount(0);
for (Student student : dataList) {
tableModel.addRow(new Object[]{
tableModel.getRowCount() + 1,
student.getFullname(),
student.getEmail(),
student.getAddress()
});
}
}
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
// TODO add your handling code here:
txtFullname.setText("");
txtAddress.setText("");
txtEmail.setText("");
}//GEN-LAST:event_btnResetActionPerformed
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
// TODO add your handling code here:
int index = tblStudent.getSelectedRow();
if (index >= 0) {
StudentDAO.delete(dataList.get(index).getId());
dataList.remove(index);
showData();
} else {
JOptionPane.showMessageDialog(rootPane, "Vui long chon ban ghi can xoa!!!");
}
}//GEN-LAST:event_btnDeleteActionPerformed
private void btnLoadDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadDataActionPerformed
dataList = StudentDAO.list();
showData();
}//GEN-LAST:event_btnLoadDataActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnLoadData;
private javax.swing.JButton btnReset;
private javax.swing.JButton btnSave;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblStudent;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtEmail;
private javax.swing.JTextField txtFullname;
// End of variables declaration//GEN-END:variables
}
#Student.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package java2.lesson06;
/**
*
* @author diepvan
*/
public class Student {
String fullname, email, address;
int id;
public Student() {
}
public Student(String fullname, String email, String address) {
this.fullname = fullname;
this.email = email;
this.address = address;
}
public Student(int id, String fullname, String email, String address) {
this.fullname = fullname;
this.email = email;
this.address = address;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
#StudentDAO.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package java2.lesson06;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author diepvan
*/
public class StudentDAO {
public static List<Student> list() {
List<Student> dataList = new ArrayList<>();
// TODO add your handling code here:
//B1. Mo ket noi toi database
Connection con = null;
PreparedStatement statement = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/C2109I", "root", "");
//B2. Thuc hien truy van
String sql = "select * from users";
statement = con.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
Student std = new Student(resultSet.getInt("id"),
resultSet.getString("fullname"),
resultSet.getString("email"),
resultSet.getString("address")
);
dataList.add(std);
}
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
} finally {
//B3. Dong ket noi
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return dataList;
}
public static void insert(Student std) {
//B1. Mo ket noi toi database
Connection con = null;
PreparedStatement statement = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/C2109I", "root", "");
//B2. Thuc hien truy van
String sql = "insert into users(fullname, email, address) values (?, ?, ?)";
statement = con.prepareStatement(sql);
statement.setString(1, std.getFullname());
statement.setString(2, std.getEmail());
statement.setString(3, std.getAddress());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
} finally {
//B3. Dong ket noi
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void update(Student std) {
//B1. Mo ket noi toi database
Connection con = null;
PreparedStatement statement = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/C2109I", "root", "");
//B2. Thuc hien truy van
String sql = "update users set fullname=?, email=?, address=? where id=?";
statement = con.prepareStatement(sql);
statement.setString(1, std.getFullname());
statement.setString(2, std.getEmail());
statement.setString(3, std.getAddress());
statement.setInt(4, std.getId());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
} finally {
//B3. Dong ket noi
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void delete(int id) {
//B1. Mo ket noi toi database
Connection con = null;
PreparedStatement statement = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/C2109I", "root", "");
//B2. Thuc hien truy van
String sql = "delete from users where id = ?";
statement = con.prepareStatement(sql);
statement.setInt(1, id);
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
} finally {
//B3. Dong ket noi
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(con != null) {
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
#VeMayBay.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package java2.lesson06;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author diepvan
*/
public class VeMayBay {
String code;
String name;
String departure;
String luggage;
float price;
public VeMayBay() {
}
public String getCode() {
return code;
}
public boolean setCode(String code) {
//Check VietjetAir => VJABB
Pattern pattern = Pattern.compile("VJ[1-9]{1}[0-9]{2}$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(code);
boolean matchFound = matcher.find();
if(matchFound) {
this.code = code;
return true;
}
//VNABBC -> Vietnam airline
pattern = Pattern.compile("VN[1-9]{1}[0-9]{2}[0-9]?$", Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(code);
matchFound = matcher.find();
if(matchFound) {
this.code = code;
return true;
}
//JETABB -> Jet Start
pattern = Pattern.compile("JET[1-9]{1}[0-9]{2}$", Pattern.CASE_INSENSITIVE);
matcher = pattern.matcher(code);
matchFound = matcher.find();
if(matchFound) {
this.code = code;
return true;
}
return false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDeparture() {
return departure;
}
public void setDeparture(String departure) {
this.departure = departure;
}
public String getLuggage() {
return luggage;
}
public void setLuggage(String luggage) {
this.luggage = luggage;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public void input() {
Scanner scan = new Scanner(System.in);
System.out.println("Nhap ma ve may bay: ");
String code2 = scan.nextLine();
while(!setCode(code2)) {
System.out.println("Nhap lai: ");
code2 = scan.nextLine();
}
System.out.println("Nhap ten ve may bay: ");
name = scan.nextLine();
System.out.println("Nhap ngay khoi hanh: ");
departure = scan.nextLine();
System.out.println("Nhap hanh ly: ");
luggage = scan.nextLine();
System.out.println("Nhap gia: ");
price = Float.parseFloat(scan.nextLine());
}
public void display() {
System.out.println(this);
}
@Override
public String toString() {
return "code=" + code + ", name=" + name + ", departure=" + departure + ", luggage=" + luggage + ", price=" + price + "\n";
}
public void parseLine(String line) {
String[] eles = line.trim().split(",");
//code
String[] params = eles[0].split("=");
code = params[1].trim();
params = eles[1].split("=");
name = params[1].trim();
params = eles[2].split("=");
departure = params[1].trim();
params = eles[3].split("=");
luggage = params[1].trim();
params = eles[4].split("=");
price = Float.parseFloat(params[1].trim());
}
public String getFileName() {
if(code.startsWith("VJ")) return "vj.txt";
if(code.startsWith("VN")) return "vn.txt";
if(code.startsWith("JET")) return "jet.txt";
return "other.txt";
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)