You are on page 1of 28

Project Source Code:

First Creat Product Class


Start Product Class

package java_project_1_2;

public class Product {

private int id;


private String name;
private float price;
private String addDate;
private byte[] picture;

public Product(int pid, String pname, float pprice, String pAddDate, byte[] pimg)
{
this.id = pid;
this.name = pname;
this.price = pprice;
this.addDate = pAddDate;
this.picture = pimg;
}

public int getId()


{
return id;
}

public String getName()


{
return name;
}

public float getPrice()


{
return price;
}

public String getAddDate()


{
return addDate;
}
public byte[] getImage()
{
return picture;
}

EndProduct Class

package java_project_1_2;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

/**
*
* @author 1BestCsharp.blogspot.com
*/
public class Main_Window extends javax.swing.JFrame {

/**
* Creates new form Main_Window
*/
public Main_Window() {
initComponents();
Show_Products_In_JTable();
}

String ImgPath = null;


int pos = 0;

// Function To Connect To MySQL Database


public Connection getConnection()
{
Connection con = null;

try {
con =
DriverManager.getConnection("jdbc:mysql://localhost/products_db2","root","");
return con;
} catch (SQLException ex) {
Logger.getLogger(Main_Window.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}

// Check Input Fields


public boolean checkInputs()
{
if(
txt_name.getText() == null
|| txt_price.getText() == null
|| txt_AddDate.getDate() == null
){
return false;
}
else{
try{
Float.parseFloat(txt_price.getText());
return true;
}catch(Exception ex)
{
return false;
}
}
}

// Function To Resize The Image To Fit Into JLabel


public ImageIcon ResizeImage(String imagePath, byte[] pic)
{
ImageIcon myImage = null;

if(imagePath != null)
{
myImage = new ImageIcon(imagePath);
}else{
myImage = new ImageIcon(pic);
}

Image img = myImage.getImage();


Image img2 = img.getScaledInstance(lbl_image.getWidth(), lbl_image.getHeight(),
Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(img2);
return image;

// Display Data In JTable:


// 1 - Fill ArrayList With The Data

public ArrayList<Product> getProductList()


{
ArrayList<Product> productList = new ArrayList<Product>();
Connection con = getConnection();
String query = "SELECT * FROM products";

Statement st;
ResultSet rs;

try {

st = con.createStatement();
rs = st.executeQuery(query);
Product product;

while(rs.next())
{
product = new
Product(rs.getInt("id"),rs.getString("name"),Float.parseFloat(rs.getString("price")),rs.ge
tString("add_date"),rs.getBytes("image"));
productList.add(product);
}

} catch (SQLException ex) {


Logger.getLogger(Main_Window.class.getName()).log(Level.SEVERE, null, ex);
}
return productList;

// 2 - Populate The JTable

public void Show_Products_In_JTable()


{
ArrayList<Product> list = getProductList();
DefaultTableModel model = (DefaultTableModel)JTable_Products.getModel();
// clear jtable content
model.setRowCount(0);
Object[] row = new Object[4];
for(int i = 0; i < list.size(); i++)
{
row[0] = list.get(i).getId();
row[1] = list.get(i).getName();
row[2] = list.get(i).getPrice();
row[3] = list.get(i).getAddDate();

model.addRow(row);
}

// Show Data In Inputs


public void ShowItem(int index)
{
txt_id.setText(Integer.toString(getProductList().get(index).getId()));
txt_name.setText(getProductList().get(index).getName());
txt_price.setText(Float.toString(getProductList().get(index).getPrice()));

try {
Date addDate = null;
addDate = new SimpleDateFormat("yyyy-MM-
dd").parse((String)getProductList().get(index).getAddDate());
txt_AddDate.setDate(addDate);
} catch (ParseException ex) {
Logger.getLogger(Main_Window.class.getName()).log(Level.SEVERE, null, ex);
}

lbl_image.setIcon(ResizeImage(null, getProductList().get(index).getImage()));
}

/**
* 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">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();


jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txt_name = new javax.swing.JTextField();
txt_id = new javax.swing.JTextField();
txt_price = new javax.swing.JTextField();
txt_AddDate = new com.toedter.calendar.JDateChooser();
lbl_image = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
JTable_Products = new javax.swing.JTable();
Btn_Choose_Image = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
Btn_Insert = new javax.swing.JButton();
Btn_First = new javax.swing.JButton();
Btn_Previous = new javax.swing.JButton();
Btn_Last = new javax.swing.JButton();
Btn_Next = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jPanel1.setBackground(new java.awt.Color(255, 255, 204));

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N


jLabel1.setText("ID:");

jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N


jLabel2.setText("Name:");

jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N


jLabel3.setText("Price:");

jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N


jLabel4.setText("Add Date:");

jLabel5.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N


jLabel5.setText("Image:");
txt_name.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
txt_name.setPreferredSize(new java.awt.Dimension(59, 50));

txt_id.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


txt_id.setEnabled(false);
txt_id.setPreferredSize(new java.awt.Dimension(59, 50));

txt_price.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


txt_price.setPreferredSize(new java.awt.Dimension(59, 50));

txt_AddDate.setDateFormatString("yyyy-MM-dd");
txt_AddDate.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N

lbl_image.setBackground(new java.awt.Color(204, 255, 255));


lbl_image.setOpaque(true);

JTable_Products.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {

},
new String [] {
"ID", "Name", "Price", "Add Date"
}
));
JTable_Products.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
JTable_ProductsMouseClicked(evt);
}
});
jScrollPane1.setViewportView(JTable_Products);

Btn_Choose_Image.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N


Btn_Choose_Image.setText("Choose Image");
Btn_Choose_Image.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn_Choose_ImageActionPerformed(evt);
}
});

jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


jButton2.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/Renew.png
"))); // NOI18N
jButton2.setText("Update");
jButton2.setIconTextGap(15);
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jButton3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


jButton3.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/delete.png"
))); // NOI18N
jButton3.setText("Delete");
jButton3.setIconTextGap(15);
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

Btn_Insert.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


Btn_Insert.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/add.png")))
; // NOI18N
Btn_Insert.setText("Insert");
Btn_Insert.setIconTextGap(15);
Btn_Insert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn_InsertActionPerformed(evt);
}
});

Btn_First.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


Btn_First.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/first.png")))
; // NOI18N
Btn_First.setText("First");
Btn_First.setIconTextGap(15);
Btn_First.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn_FirstActionPerformed(evt);
}
});

Btn_Previous.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


Btn_Previous.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/previous.pn
g"))); // NOI18N
Btn_Previous.setText("Previous");
Btn_Previous.setIconTextGap(15);
Btn_Previous.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn_PreviousActionPerformed(evt);
}
});

Btn_Last.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


Btn_Last.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/last.png")))
; // NOI18N
Btn_Last.setText("Last");
Btn_Last.setIconTextGap(15);
Btn_Last.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn_LastActionPerformed(evt);
}
});

Btn_Next.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N


Btn_Next.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/JAVA_VIDEOS_TUTORIALS/icons/next.png"))
); // NOI18N
Btn_Next.setText("Next");
Btn_Next.setIconTextGap(15);
Btn_Next.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Btn_NextActionPerformed(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(33, 33, 33)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TR
AILING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE
ADING, false)
.addComponent(Btn_Choose_Image, javax.swing.GroupLayout.DEFAULT_SIZE, 227,
Short.MAX_VALUE)
.addComponent(txt_AddDate, javax.swing.GroupLayout.PREFERRED_SIZE, 125,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_id, javax.swing.GroupLayout.PREFERRED_SIZE, 109,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_name, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txt_price, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_image, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(Btn_Insert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3)
.addGap(45, 45, 45)
.addComponent(Btn_First)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Btn_Next)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Btn_Previous)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Btn_Last)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE
ADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignmen
t.BASELINE)
.addComponent(txt_id, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(9, 9, 9)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignmen
t.BASELINE)
.addComponent(txt_name, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(14, 14, 14)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignmen
t.BASELINE)
.addComponent(jLabel3)
.addComponent(txt_price, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignmen
t.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel4))
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED
)
.addComponent(txt_AddDate, javax.swing.GroupLayout.PREFERRED_SIZE, 41,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignmen
t.BASELINE)
.addComponent(jLabel5)
.addComponent(lbl_image, javax.swing.GroupLayout.PREFERRED_SIZE, 167,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Btn_Choose_Image, javax.swing.GroupLayout.PREFERRED_SIZE,
36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54,
Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BA
SELINE)
.addComponent(Btn_Insert, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn_First, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn_Next, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn_Previous, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Btn_Last, javax.swing.GroupLayout.PREFERRED_SIZE, 40,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

pack();
}// </editor-fold>

// Button Browse Image From Your Computer


private void Btn_Choose_ImageActionPerformed(java.awt.event.ActionEvent evt)
{

JFileChooser file = new JFileChooser();


file.setCurrentDirectory(new File(System.getProperty("user.home")));

FileNameExtensionFilter filter = new FileNameExtensionFilter("*.images",


"jpg","png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION)
{
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
lbl_image.setIcon(ResizeImage(path, null));
ImgPath = path;
}
else{
System.out.println("No File Selected");
}

// Button Insert Data Into MySQL Database


// 1 - Check If The imgPath Is Not Null And The Inputs Are Not Empty
// 2 - Insert The Data
private void Btn_InsertActionPerformed(java.awt.event.ActionEvent evt)
{
if(checkInputs() && ImgPath != null)
{
try {
Connection con = getConnection();
PreparedStatement ps = con.prepareStatement("INSERT INTO
products(name,price,add_date,image)"
+ "values(?,?,?,?) ");
ps.setString(1, txt_name.getText());
ps.setString(2, txt_price.getText());

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


String addDate = dateFormat.format(txt_AddDate.getDate());
ps.setString(3, addDate);

InputStream img = new FileInputStream(new File(ImgPath));


ps.setBlob(4, img);
ps.executeUpdate();
Show_Products_In_JTable();

JOptionPane.showMessageDialog(null, "Data Inserted");


} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}else{
JOptionPane.showMessageDialog(null, "One Or More Field Are Empty");
}

// only for test


System.out.println("Name => "+txt_name.getText());
System.out.println("Price => "+txt_price.getText());
System.out.println("Image => "+ImgPath);
}

// Button Update Data From MySQL Database


// 1 - Check If Inputs Is Not Null
// If The imgPath Is Not Null Update Also The Image
// else don't update the Image
// 2 - Update The Data
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{

if(checkInputs() && txt_id.getText() != null)


{
String UpdateQuery = null;
PreparedStatement ps = null;
Connection con = getConnection();

// update without image


if(ImgPath == null)
{
try {
UpdateQuery = "UPDATE products SET name = ?, price = ?"
+ ", add_date = ? WHERE id = ?";
ps = con.prepareStatement(UpdateQuery);

ps.setString(1, txt_name.getText());
ps.setString(2, txt_price.getText());

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


String addDate = dateFormat.format(txt_AddDate.getDate());

ps.setString(3, addDate);

ps.setInt(4, Integer.parseInt(txt_id.getText()));

ps.executeUpdate();
Show_Products_In_JTable();
JOptionPane.showMessageDialog(null, "Product Updated");

} catch (SQLException ex) {


Logger.getLogger(Main_Window.class.getName()).log(Level.SEVERE, null, ex);
}

}
// update With Image
else{
try{
InputStream img = new FileInputStream(new File(ImgPath));

UpdateQuery = "UPDATE products SET name = ?, price = ?"


+ ", add_date = ?, image = ? WHERE id = ?";

ps = con.prepareStatement(UpdateQuery);

ps.setString(1, txt_name.getText());
ps.setString(2, txt_price.getText());

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");


String addDate = dateFormat.format(txt_AddDate.getDate());

ps.setString(3, addDate);

ps.setBlob(4, img);

ps.setInt(5, Integer.parseInt(txt_id.getText()));

ps.executeUpdate();
Show_Products_In_JTable();
JOptionPane.showMessageDialog(null, "Product Updated");

}catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}else{
JOptionPane.showMessageDialog(null, "One Or More Fields Are Empty Or Wrong");
}

// Button Delete The Data From MySQL Database


private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{

if(!txt_id.getText().equals(""))
{
try {
Connection con = getConnection();
PreparedStatement ps = con.prepareStatement("DELETE FROM products WHERE
id = ?");
int id = Integer.parseInt(txt_id.getText());
ps.setInt(1, id);
ps.executeUpdate();
Show_Products_In_JTable();
JOptionPane.showMessageDialog(null, "Product Deleted");
} catch (SQLException ex) {
Logger.getLogger(Main_Window.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Product Not Deleted");
}

}else{
JOptionPane.showMessageDialog(null, "Product Not Deleted : No Id To Delete");
}

// JTable Mouse Clicked


// Display The Selected Row Data Into JTextFields
// And The Image Into JLabel
private void JTable_ProductsMouseClicked(java.awt.event.MouseEvent evt)
{

int index = JTable_Products.getSelectedRow();


ShowItem(index);
}

// Button First Show The First Record


private void Btn_FirstActionPerformed(java.awt.event.ActionEvent evt)
{
pos = 0;
ShowItem(pos);
}

// Button Last Show The Last Record


private void Btn_LastActionPerformed(java.awt.event.ActionEvent evt)
{
pos = getProductList().size()-1;
ShowItem(pos);
}

// Button Next Show The Next Record


private void Btn_NextActionPerformed(java.awt.event.ActionEvent evt)
{

pos++;

if(pos >= getProductList().size())


{
pos = getProductList().size()-1;
}

ShowItem(pos);

}
// Button Previous Show The Previous Record
private void Btn_PreviousActionPerformed(java.awt.event.ActionEvent evt)
{

pos--;

if(pos < 0)
{
pos = 0;
}

ShowItem(pos);

/**
* @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(Main_Window.class.getName()).log(java.util.logging.L
evel.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main_Window.class.getName()).log(java.util.logging.L
evel.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main_Window.class.getName()).log(java.util.logging.L
evel.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main_Window.class.getName()).log(java.util.logging.L
evel.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main_Window().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton Btn_Choose_Image;
private javax.swing.JButton Btn_First;
private javax.swing.JButton Btn_Insert;
private javax.swing.JButton Btn_Last;
private javax.swing.JButton Btn_Next;
private javax.swing.JButton Btn_Previous;
private javax.swing.JTable JTable_Products;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
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.JLabel lbl_image;
private com.toedter.calendar.JDateChooser txt_AddDate;
private javax.swing.JTextField txt_id;
private javax.swing.JTextField txt_name;
private javax.swing.JTextField txt_price;
// End of variables declaration
}
Creating a JDBC Application in NetBeans: A Step-by-
Step Guide
 May 3, 2017
 By Manoj Debnath
 Send Email »
 More Articles »

This article is an attempt to aid readers who find difficulty in creating a JDBC application in NetBeans.
The idea is to keep things as simple as possible so that one can go hands-on right from the beginning.
Being able to see your first application running is not only fun but also improves one's theoretical base. In
computing, there are several way to do one simple thing. This step-by-step guide is just one of them. The
application created is nothing fancy, of course; including the SQL statement used for DDL and DML are a
bare minimum. Once the steps provided in this article are implemented, one can make one's own choices
and preferences; until then, follow this article. So without further ado, let's start.

Step 0: What We Need (Rather, What We Have Used in This Article)


 NetBeans 8.2
 JDK 8
 MySQL 5
That's all…and oh! You also need a Linux platform. The idea is same for Windows as well, except for
the Terminal command used for setting up your MySQL user account in part of Step 1.

Step 1: Setting Up Your MySQL User Account


Assuming that the MySQL database is installed properly, we'll create a user account to work with the
database. It is always a good idea to use a different user account to play with the database rather than
always using the default root user account.

 Open Linux Terminal and start the database server by executing the command mysql, as
follows. This will start the MySQL Server.
$ service mysql start or restart

 Then, start the MySQL monitor to set up your user account.


o Post a comment
o Email Article
o Print Article
o Share Articles

$ mysql -h localhost -u root

Eight Tips for Choosing an MSP to Support an Azure Deployment


Download Now

The -h option indicates the host on which MySQL service is running. The -u option indicates a
user account; root is a default user. If a root password is set (during installation), add -p (it will
prompt you for a password); otherwise, leave it blank.
 In the mysql> prompt, type:
USE mysql;

This will select the built-in database called mysql, which stores server information such as user
accounts and their privileges.

 Add a new account to the mysqlbuilt-in database with all required privileges.
 create user 'mickey'@'localhost' identified by 'mickey';

 grant select, create, drop, references, insert, update,

 delete, execute on *.* to 'mickey'@'localhost';

This will create a user named mickey with password mickey.

 Type the command exit; to terminate MySQL monitor


Step 2: Create the Database
The MySQL database (which we'll create down the line with the CREATE command) is like a folder where
all the related tables are stored. So, in most cases, when the theme of the database changes, we keep
the table that adheres to the theme encompassed within a logical area called the database. For example,
a library database may contain tables such asbooks, authors, publisher, borrowing, and so forth. But,
before we create the database, we must log in to MySQL with the new user we have just created (if you
have not created any, use the default root user).

 Log in again with the new user account. Because we have used "set password" for this user, -p
will prompt for it.
mysql -h localhost -u mickey -p

 Create a database. Here, testdbis like a folder, a container that will contain all the tables we will
create.
 CREATE testdb;

 USE testdb;

 Now, create tables with the following SQL DDL:


 create table books

 (

 isbn varchar(20) primary key,

 title varchar(50),

 edition varchar(20),

 price float(10,2)

 );


 create table authors

 (

 author_id int primary key,

 author_name varchar(50)

 );

 create table book_by_author

 (

 isbn varchar(20),

 author_id int,

 foreign key(isbn)

 references books(isbn),

 foreign key(author_id)

 references authors(author_id)

 );

Insert some dummy data. This will help in testing the application later.

insert into books values('123456','Discrete Math',


'Second',56.78);
insert into books values('234567','Integral Calculus',
'Second',92.73);
insert into books values('345678','Differential Calculus',
'First',57.86);
insert into books values('456789','Graph Theory',
'Second',33.8);
insert into books values('567890','Set Theory',
'Fourth',34.89);
insert into books values('102938','Numerical Methods',
'Third',98.46);

insert into authors values(1,'CS Liu');


insert into authors values(2,'N Deo');
insert into authors values(3,'Rogers');
insert into authors values(4,'Saxena');
insert into authors values(5,'Sandip');
insert into authors values(6,'Srivastava');
insert into authors values(7,'Jha');

insert into book_by_author values('123456',1);


insert into book_by_author values('123456',2);
insert into book_by_author values('123456',3);
insert into book_by_author values('234567',4);
insert into book_by_author values('234567',5);
insert into book_by_author values('345678',6);
insert into book_by_author values('456789',7);
insert into book_by_author values('567890',4);
insert into book_by_author values('102938',6);

 Terminate MySQl monitor with the exit; command.


Up to this point, there has been nothing to do with Java; we are basically dealing with SQL DDL in
MySQL Monitor. From the next step onwards, we'll deal with Java and NetBeans.

Step 3: Create a Java Project


Open the NetBeans IDE and create a Java Project in the following manner:

1. File → New Project; a window will appear. Select Java from the Categories list and Java
Application from the Projects list. Click Next.
2. In the New Java Application window, enter the name location of the project. Optionally,
check Use Dedicated Folder for Storing Librariesor un-check it. It does not matter, at least for our
current project, but the purpose is clearly stated in the help section; let's not restate it here.
Figure 1: Assigning a project name and location

3. Click Finish. This will create a Java project environment in NetBeans.

Figure 2: The Java project environment is created

Step 4: Add the MySQL JDBC Driver


 Because it is a JDBC project and we opt to connect to a MySQL database, we need MySQL
JDBC Driver. It is basically a vendor-specific Type 4 driver that bridges the communication gap
between our application and the database. If you want to connect to any other database, look for
that database-specific JDBC driver. A JDBC Driver for almost all major databases (Oracle,
PostgreSQL, and so on) is available in the relevant vendor sites.
 Right-click the project name in the Projects tree view → Properties.
 Select Libraries from the Categoriestree view.

Figure 3: Selecting Libraries from the Categories tree view

 Click the Add Library button. An Add Library window will appear. If the MySQL JDBC Driver is
not present in the available libraries list, click the Import…button. Then, click the MySQL JDBC
Driver from the available libraries list.

Note: The MySQL JDBC Driver is already shipped


with NetBeans. There is no need to install it separately.
Other drivers, which may not be shipped with
NetBeans, may need to be imported as a separate jar
file. In such a case, use the Add JAR/Folder button to
import it in the current project.

Figure 4: Adding a Library

 If the import is successful, the imported jar file will be shown in the projects list.

Figure 5: The imported jar file is shown in the projects list

 Now that everything is set, we can start our code in Java.


Step 5: Creating the Application
There a few thing common to Java code in implementing a JDBC application. The package that contains
all the required classes and interfaces for JDBC programming is java.sql. The exceptions that may occur
are handled by the object of the SQLException reference defined in the same package.
1. Connecting to the database
Database connection is established by creating a Connection object. The Connection is an
interface and the object that implements the Connection interface manages the connection
between Java and the database. A reference to the Connection object is created with the help of
the overloaded static method getConnection(), defined in the DriverManager class. One of the
overloaded getConnection() methods takes three parameters.

 Database URL of the format jdbc:mysql://hostname:portNumber/databaseName for


MySQL. This format may change when connecting to other databases.
 Database user name
 Database password
2. Executing the SQL query
Next, we need an object reference to the Statement interface to submit SQL statements to the
database.

3. Processing the query result


The result of the query fired through the Statement object is contained by an object of
the ResultSet interface.

When we put these together, it looks like this. This is the code we write inside
the SimpleJDBCApplication.java source file, which basically fetches the record we have inserted in
the books table we have created.

package simplejdbcapplication;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SimpleJDBCApplication {

static final String DB_URL =


"jdbc:mysql://localhost:3306/testdb";
static final String DB_DRV =
"com.mysql.jdbc.Driver";
static final String DB_USER = "mickey";
static final String DB_PASSWD = "mickey";
public static void main(String[] args){

Connection connection = null;


Statement statement = null;
ResultSet resultSet = null;

try{
connection=DriverManager.getConnection
(DB_URL,DB_USER,DB_PASSWD);
statement=connection.createStatement();
resultSet=statement.executeQuery
("SELECT * FROM books");
while(resultSet.next()){
System.out.printf("%s\t%s\t%s\t%f\n",
resultSet.getString(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getFloat(4));
}

}catch(SQLException ex){
}finally{
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException ex) {
}
}
}
}

Step 6: Execute the Application


Click Run→ Run Project, or press Ctrl+F11. This will compile and execute the project.

Conclusion
That's all you need to kick start a JDBC application in NetBeans. Now, to play with the code what you can
do is implement insert, update, and delete operations.

References
Refer to the Java Documentation and have a look at the following interfaces apart from what we have
used in the preceding code. They will be helpful in implementing new operations.

 java.sql.ResultSetMetadata
 java.sql.DatabaseMetaData
 java.sql.PreparedStatement
Here are a few links to JDBC-related articles which one might find interesting.

 http://www.developer.com/java/data/discovering-database-metadata-with-the-jdbc-
metadata-api.html
 http://www.developer.com/java/j2me/working-with-embedded-databases-in-java.html
 http://www.developer.com/db/dynamic-database-creation-with-jdbc.html
 http://www.developer.com/db/from-data-models-to-relational-design.html
 http://www.developer.com/java/creating-a-jdbc-gui-application.html
 http://www.developer.com/java/working-with-the-jdbc-rowset-api.html
 http://www.developer.com/java/data/manipulating-a-database-with-jdbc.html
 http://www.developer.com/java/data/jdbc-application-design-consideration.html

You might also like