การต่อ DATABASE MySQL พร้อม Insert Image 
Insert และ เอา รูป จาก Database มาแสดง
1 create table ดังนี้
CREATE TABLE `customers` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(30) NOT NULL,
`surname` varchar(30) NOT NULL,
`phone` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

สร้างหน้าตาดังนี้






















ด้านซ้ายคือ ImagePanel ซึ่งมี code ดังนี้





import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class ImagePanel extends JPanel{
BufferedImage img;
public ImagePanel(){}
public void setImage(BufferedImage i){
img = i;
repaint();
}
public BufferedImage getImage(){
return img;
}
public void paint(Graphics g){
g.drawImage(img, 0, 0,this.getWidth(),this.getHeight(), this);
}
}



code ของหน้าจอหลัก

import java.awt.EventQueue;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.*;

public class InsertProduct extends JFrame
{

private JPanel contentPane;
private JTextField txt_name;
private JTextField txt_price;
private ImagePanel imagePanel;

/**
* Launch the application.
*/
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e){}
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
InsertProduct frame = new InsertProduct();
frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public InsertProduct()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

imagePanel = new ImagePanel();
imagePanel.setBounds(10, 11, 248, 240);
contentPane.add(imagePanel);

JButton btnBrowse = new JButton("browse image");
btnBrowse.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JFileChooser fc = new JFileChooser("c://");
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
if (res == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
// this.
try
{
imagePanel.setImage(ImageIO.read(file));
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
btnBrowse.setBounds(268, 11, 156, 23);
contentPane.add(btnBrowse);

JLabel lblProductName = new JLabel("product name");
lblProductName.setBounds(268, 51, 102, 14);
contentPane.add(lblProductName);

txt_name = new JTextField();
txt_name.setBounds(268, 74, 156, 23);
contentPane.add(txt_name);
txt_name.setColumns(10);

JLabel lblPricePerUnit = new JLabel("price per unit");
lblPricePerUnit.setBounds(268, 108, 102, 14);
contentPane.add(lblPricePerUnit);

txt_price = new JTextField();
txt_price.setColumns(10);
txt_price.setBounds(268, 131, 156, 23);
contentPane.add(txt_price);

JButton btn_insert = new JButton("Insert");
btn_insert.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/yyy", "root", "1234");

Class.forName("com.mysql.jdbc.Driver");

String price = txt_price.getText();
String name = txt_name.getText();

String insert = "INSERT INTO product(id,name,price_per_unit,image) " + " VALUES (0,?,?,?)";

PreparedStatement preparedStmt = con.prepareStatement(insert);
ByteArrayOutputStream buff = new ByteArrayOutputStream();
ImageIO.write(imagePanel.getImage(), "PNG", buff);
byte[] buff_temp = buff.toByteArray();
ByteArrayInputStream inBuff = new ByteArrayInputStream(buff_temp);

preparedStmt.setString(1, name);
preparedStmt.setString(2, price);
preparedStmt.setBinaryStream(3, inBuff, buff_temp.length);

preparedStmt.execute();
System.out.println("finish");
con.close();
} catch (Exception ee)
{
ee.printStackTrace();
}
}
});
btn_insert.setBounds(269, 185, 89, 23);
contentPane.add(btn_insert);
}
}
class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter{
public boolean accept(File f){
if (f.getName().toLowerCase().endsWith(".jpeg"))
return true;
if (f.getName().toLowerCase().endsWith(".jpg"))
return true;
if (f.isDirectory())
return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}




จะเห็นว่า ตอนInsert จะใช้ PreparedStatement มาช่วย
ByteArrayOutputStream buff = new ByteArrayOutputStream();
ImageIO.write(imagePanel.getImage(), "PNG", buff);
byte[] buff_temp = buff.toByteArray();
ByteArrayInputStream inBuff = new ByteArrayInputStream(buff_temp);

ส่วนนี้ใช้ Save Image ลง Memory ก่อน แล้วค่อย Save ลง DATABASE อีกทีหนึ่ง


ดึงข้อมูลพ้อมรูปมาแสดง




import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class ProductPanel extends JPanel
{
public ProductPanel()
{
setLayout(null);
imagePanel = new ImagePanel();
imagePanel.setBounds(0, 0, 223, 109);
add(imagePanel);
label_id = new JLabel("New label");
label_id.setBounds(322, 9, 118, 26);
add(label_id);
label_name = new JLabel("New label");
label_name.setBounds(322, 46, 118, 26);
add(label_name);
label_price = new JLabel("New label");
label_price.setBounds(322, 83, 118, 26);
add(label_price);
lblUd = new JLabel("id");
lblUd.setBounds(233, 9, 62, 26);
add(lblUd);
lblName = new JLabel("name");
lblName.setBounds(233, 46, 62, 26);
add(lblName);
lblPricePerUnit = new JLabel("price per unit");
lblPricePerUnit.setBounds(233, 83, 79, 26);
add(lblPricePerUnit);
}

public void setParam(int id, String name, double price, BufferedImage img)
{
this.id=id;
this.name= name;
this.price=price;
this.img=img;

label_id.setText(""+ this.id);
label_name.setText(""+ this.name);
label_price.setText(""+ this.price);

imagePanel.setImage(img);
}

public int id;
public String name;
public double price;
public BufferedImage img;

private JLabel label_price;
private JLabel label_name;
private JLabel label_id;
private ImagePanel imagePanel;
private JLabel lblUd;
private JLabel lblName;
private JLabel lblPricePerUnit;

}




import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.sql.*;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;


public class selectProduct extends JFrame
{

private JPanel contentPane;

public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
selectProduct frame = new selectProduct();
frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}

public selectProduct()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
// //////////////////////////////////
try
{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/yyy", "root", "1234");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM product");
Class.forName("com.mysql.jdbc.Driver");

int i=0;
while (rs.next())
{
ProductPanel pp = new ProductPanel();
BufferedImage img = ImageIO.read(rs.getBinaryStream(4));
pp.setParam(rs.getInt(1), rs.getString(2), rs.getDouble(3), img);
pp.setBounds(0, i*120 + 20, 500, 120);
this.contentPane.add(pp);

System.out.println(pp.id +" "+ pp.name);
i++;
}

} catch (Exception ee)
{
ee.printStackTrace();
}

}
}



อาจต้องมีการ set ค่าในดรสำ my.ini สำหรับ ขนาดของ รูป
max_allowed_packet=500M

Comments

Add Comment
Comments are not available for this entry.