Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

Chèn hình xuống MS SQL server sử dụng GUI

package vovanhai.wordpress.com;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class SaveImage2MSSQLServer_GUI extends JFrame implements ActionListener{
	private JTextField tfName;
	private JLabel lbPic;
	private JButton btLoad,btnSave,btnClear;
	private String filePath="";

	public SaveImage2MSSQLServer_GUI() {
		setTitle("https://vovanhai.wordpress.com");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(600,400);
		JLabel lbl=new JLabel("Save Image to MSSQL Database",JLabel.CENTER);
		lbl.setFont(new Font("Arial",Font.BOLD,20));
		createGUI();
	}

	private void createGUI() {
		Box b=Box.createVerticalBox();
		Box b1=Box.createHorizontalBox();
		Box b2=Box.createHorizontalBox();
		b.add(b1);b.add(Box.createVerticalStrut(10));
		b.add(b2);b.add(Box.createVerticalStrut(10));
		b1.add(new JLabel("Demo"));
		b2.add(new JLabel("File Path:",JLabel.RIGHT));
		b2.add(tfName=new JTextField(20));
		b2.add(btLoad=new JButton("Load Image"));btLoad.addActionListener(this);
		this.add(b,BorderLayout.NORTH);
		JPanel pCen=new JPanel(new BorderLayout());
		pCen.setBorder(BorderFactory.createTitledBorder("Display Image"));
		this.add(pCen);
		pCen.add(lbPic=new JLabel("",JLabel.CENTER));

		JPanel pBot=new JPanel();
		pBot.add(btnSave=new JButton("Save to DB"));
		btnSave.addActionListener(this);
		pBot.add(btnClear=new JButton("Clear Image"));
		btnClear.addActionListener(this);

		this.add(pBot,BorderLayout.SOUTH);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Object o=e.getSource();
		if(o.equals(btLoad)){
			JFileChooser fc=new JFileChooser(".");
			if(fc.showDialog(null,"Chọn hình")==JFileChooser.APPROVE_OPTION){
				try {
					filePath=fc.getSelectedFile().getAbsolutePath();
					ImageIcon icon=new ImageIcon(filePath);
					tfName.setText(filePath);
					lbPic.setIcon(icon);
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null, e1.getMessage());
				}
			}
		}
		else if(o.equals(btnSave)){
			try {
				Icon xx= lbPic.getIcon();
				if(xx.getIconHeight()==-1||xx.getIconWidth()==-1){
					JOptionPane.showMessageDialog(null, 
							"Không có hình hoặc file bạn chọn không phải file hình.");
					return;
				}
				Connection conn=getConnection();
				String sql="insert into tblImages values (?,?)";

				FileInputStream fis = null;
				PreparedStatement ps = null;
				try {
					conn.setAutoCommit(false);
					File file = new File(filePath);
					fis = new FileInputStream(file);
					ps = conn.prepareStatement(sql);
					ps.setString(1, tfName.getText());
					ps.setBinaryStream(2, fis, (int) file.length());
					ps.executeUpdate();
					conn.commit();
					JOptionPane.showMessageDialog(null, "Insert Completed");
				} finally {
					ps.close();
					fis.close();
				}
			} catch (Exception e1) {
				JOptionPane.showMessageDialog(null, e1.getMessage());
			}
		}
		else if(o.equals(btnClear)){
			tfName.setText("");
			lbPic.setIcon(null);
		}
	}
	/**
	 * Tạo kết nối đền cơ sở dữ liệu 
	 * @return Connection
	 * @throws Exception
	 */
	private Connection getConnection()throws Exception{
		Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		String url="jdbc:sqlserver://localhost:1433;databaseName=TestImageDB";
		Connection conn=DriverManager.getConnection(url,"sa","");
		return conn;
	}
	
	public static void main(String[] args) {
		new SaveImage2MSSQLServer_GUI().setVisible(true);
	}
}

Kết quả:
Insert Image 2 DB

OK

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

 
%d bloggers like this: