By GokiSoft.com|
23:20 29/10/2021|
Java Advanced
[Video] Chương quản lý bán hàng - Chức năng quản lý sản phẩm - Thêm chức năng mới
Nội dung kiến thức:
- Kết nối CSDL -> Java Swing
- CRUD
CSDL: gồm 2 bảng
Mini Project: Xây dựng 1 dự án quản lý sản phẩm gồm có 2 bảng: product & category
1. View CSDL:
2. Chức năng phát triển:
- UI -> Hiển thị danh sách sản phẩm, thêm, sửa, xoá, tìm kiếm -> product
====================================================================================
Các bước phát triển dự án
B1. Tạo dự án
B2. Tải thư viên jdbc mysql driver maven -> https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.26
B3. Add vào dự án -> tai libs, maven (java netbean, java web), ant, gradle (android), composer (laravel), cocospod (ios)
B4. Phân tích dự án:
- Mapping tables -> class objects (models)
- Thiet lap cau hinh ket noi database
- Xay dung CRUD cho chuong trinh -> Lay danh sach, them, sua, xoa du lieu.
- ProductModify: Danh sach san pham, them, sua, xoa
- CategoryModify: Danh sach danh muc san pham (them, sua, xoa -> Bai tap)
- App: ProductFrame -> Quan ly san
#ProductModify.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson07;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Diep.Tran
*/
public class ProductModify {
public static List<Product> getProductList(String s) {
List<Product> dataList = new ArrayList<>();
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Truy van du lieu
String sql = "select product.*, category.id as category_id, category.name as category_name from product "
+ "left join category on category.id = product.category_id";
if(s != null && !s.isEmpty()) {
sql += " where product.title like ?";
}
statement = conn.prepareStatement(sql);
if(s != null && !s.isEmpty()) {
statement.setString(1, s);
}
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
Product p = new Product(
resultSet.getInt("id"),
resultSet.getString("title"),
resultSet.getString("thumbnail"),
resultSet.getString("content"),
resultSet.getString("created_at"),
resultSet.getString("updated_at"),
resultSet.getFloat("price"));
Category c = new Category(
resultSet.getInt("category_id"),
resultSet.getString("category_name")
);
p.setCategory(c);
dataList.add(p);
}
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return dataList;
}
public static void save(Product p) {
if(p.getId() > 0) {
update(p);
} else {
insert(p);
}
}
public static void insert(Product p) {
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Truy van du lieu
String sql = "insert into product(title, thumbnail, content, price, category_id, created_at, updated_at) "
+ "values (?, ?, ?, ?, ?, ?, ?)";
statement = conn.prepareStatement(sql);
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String strDate = dateFormat.format(date);
statement.setString(1, p.getTitle());
statement.setString(2, p.getThumbnail());
statement.setString(3, p.getContent());
statement.setFloat(4, p.getPrice());
statement.setInt(5, p.getCategory().getId());
statement.setString(6, strDate);
statement.setString(7, strDate);
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void update(Product p) {
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Truy van du lieu
String sql = "update product set title = ?, thumbnail = ?, content = ?, price = ?, category_id = ?, updated_at = ? where id = ?";
statement = conn.prepareStatement(sql);
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String strDate = dateFormat.format(date);
statement.setString(1, p.getTitle());
statement.setString(2, p.getThumbnail());
statement.setString(3, p.getContent());
statement.setFloat(4, p.getPrice());
statement.setInt(5, p.getCategory().getId());
statement.setString(6, strDate);
statement.setInt(7, p.getId());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void delete(int id) {
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Truy van du lieu
String sql = "delete from product where id = ?";
statement = conn.prepareStatement(sql);
statement.setInt(1, id);
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
#ProductFrame.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson07;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Diep.Tran
*/
public class ProductFrame extends javax.swing.JFrame {
DefaultTableModel tableModel;
List<Product> productList;
List<Category> categoryList;
int currentPos = -1;
/**
* Creates new form ProductFrame
*/
public ProductFrame() {
initComponents();
tableModel = (DefaultTableModel) productTable.getModel();
productList = ProductModify.getProductList(null);
categoryList = CategoryModify.getCategoryList();
showData();
for (Category category : categoryList) {
categoryCb.addItem(category);
}
productTable.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
currentPos = productTable.getSelectedRow();
titleTxt.setText(productList.get(currentPos).getTitle());
priceTxt.setText(productList.get(currentPos).getPrice() + "");
desTxt.setText(productList.get(currentPos).getContent());
thumbnailTxt.setText(productList.get(currentPos).getThumbnail());
for (Category category : categoryList) {
if(category.getId() == productList.get(currentPos).getId()) {
categoryCb.setSelectedItem(category);
break;
}
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
private void showData() {
tableModel.setRowCount(0);
for (Product product : productList) {
tableModel.addRow(new Object[] {
tableModel.getRowCount() + 1,
product.getTitle(),
product.getPrice(),
product.getCategory().getName()
});
}
}
/**
* 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();
titleTxt = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
priceTxt = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
thumbnailTxt = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
categoryCb = new javax.swing.JComboBox<>();
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
desTxt = new javax.swing.JTextArea();
saveBtn = new javax.swing.JButton();
delBtn = new javax.swing.JButton();
searchBtn = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
productTable = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("NHAP THONG TIN SAN PHAM"));
jLabel1.setText("Ten SP:");
jLabel2.setText("Gia:");
jLabel3.setText("Hinh Anh:");
jLabel4.setText("Danh Muc SP:");
jLabel5.setText("Mo Ta:");
desTxt.setColumns(20);
desTxt.setRows(5);
jScrollPane1.setViewportView(desTxt);
saveBtn.setText("Luu");
saveBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveBtnActionPerformed(evt);
}
});
delBtn.setText("Xoa");
delBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
delBtnActionPerformed(evt);
}
});
searchBtn.setText("Tim Kiem");
searchBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchBtnActionPerformed(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(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(thumbnailTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(categoryCb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(priceTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(56, 56, 56)
.addComponent(titleTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(31, 31, 31)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(searchBtn, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
.addComponent(delBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(saveBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(22, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(titleTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(saveBtn))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(priceTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(delBtn))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(thumbnailTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(searchBtn))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(categoryCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jLabel5)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
productTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"STT", "Ten SP", "Gia", "Danh Muc SP"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(productTable);
if (productTable.getColumnModel().getColumnCount() > 0) {
productTable.getColumnModel().getColumn(0).setResizable(false);
productTable.getColumnModel().getColumn(1).setResizable(false);
productTable.getColumnModel().getColumn(2).setResizable(false);
productTable.getColumnModel().getColumn(3).setResizable(false);
}
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(jScrollPane2))
.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)
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
// TODO add your handling code here:
String title = titleTxt.getText();
String thumbnail = thumbnailTxt.getText();
float price = Float.parseFloat(priceTxt.getText());
String content = desTxt.getText();
Category category = (Category) categoryCb.getSelectedItem();
Product p;
if(currentPos >= 0) {
p = productList.get(currentPos);
currentPos = -1;
p.setTitle(title);
p.setThumbnail(thumbnail);
p.setContent(content);
p.setPrice(price);
p.setCategory(category);
} else {
p = new Product(title, thumbnail, content, price, category);
}
ProductModify.save(p);
productList = ProductModify.getProductList(null);
showData();
titleTxt.setText("");
thumbnailTxt.setText("");
desTxt.setText("");
priceTxt.setText("");
}//GEN-LAST:event_saveBtnActionPerformed
private void delBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delBtnActionPerformed
// TODO add your handling code here:
if(currentPos == -1) {
JOptionPane.showMessageDialog(rootPane, "Ban chua chon san pham can xoa, vui long kiem tra lai.");
return;
}
int option = JOptionPane.showConfirmDialog(rootPane, "Ban chac chan muon xoa san pham nay khong?");
if(option == 0) {
ProductModify.delete(productList.get(currentPos).getId());
productList.remove(currentPos);
currentPos = -1;
showData();
}
titleTxt.setText("");
thumbnailTxt.setText("");
desTxt.setText("");
priceTxt.setText("");
}//GEN-LAST:event_delBtnActionPerformed
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchBtnActionPerformed
// TODO add your handling code here:
String titleSearch = JOptionPane.showInputDialog("Nhap ten san pham can tim kiem");
if(titleSearch == null || titleSearch.isEmpty()) {
productList = ProductModify.getProductList(null);
} else {
productList = ProductModify.getProductList("%" + titleSearch + "%");
}
showData();
}//GEN-LAST:event_searchBtnActionPerformed
/**
* @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(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProductFrame.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 ProductFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<Category> categoryCb;
private javax.swing.JButton delBtn;
private javax.swing.JTextArea desTxt;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField priceTxt;
private javax.swing.JTable productTable;
private javax.swing.JButton saveBtn;
private javax.swing.JButton searchBtn;
private javax.swing.JTextField thumbnailTxt;
private javax.swing.JTextField titleTxt;
// End of variables declaration//GEN-END:variables
}
#Product.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson07;
/**
*
* @author Diep.Tran
*/
public class Product {
int id;
String title, thumbnail, content, createdAt, updatedAt;
float price;
Category category;
public Product() {
}
public Product(String title, String thumbnail, String content, float price, Category category) {
this.title = title;
this.thumbnail = thumbnail;
this.content = content;
this.price = price;
this.category = category;
}
public Product(int id, String title, String thumbnail, String content, String createdAt, String updatedAt, float price) {
this.id = id;
this.title = title;
this.thumbnail = thumbnail;
this.content = content;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
#Config.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson07;
/**
*
* @author Diep.Tran
*/
public interface Config {
String DB_URL = "jdbc:mysql://localhost:3306/C2010G";
String USERNAME = "root";
String PASSWORD = "";
}
#CategoryModify.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson07;
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 Diep.Tran
*/
public class CategoryModify {
public static List<Category> getCategoryList() {
List<Category> dataList = new ArrayList<>();
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Truy van du lieu
String sql = "select * from category";
statement = conn.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
Category c = new Category(
resultSet.getInt("id"),
resultSet.getString("name")
);
dataList.add(c);
}
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return dataList;
}
}
#Category.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson07;
/**
*
* @author Diep.Tran
*/
public class Category {
int id;
String name;
public Category() {
}
public Category(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)