Search

'데이터베이스'에 해당되는 글 2건

  1. 2016.10.28 Java SocketServer control Image, DBConnect, String 1
  2. 2013.02.24 JAVA 데이터베이스 실습 예제 UI
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Java SocketServer control Image, DBConnect, String




package com.tistory.tansanc;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.imageio.ImageIO;

class DBConnect {
	ResultSet rs = null;
	Connection conn = null;
	Statement stmt = null;
	public DBConnect() {
		try {
			String url = "jdbc:sqlserver://192.168.10.17:1433;DatabaseName=MSSQLSERVER";
			
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			conn = DriverManager.getConnection(url, "sa", "1234");
			stmt = conn.createStatement();
			

		} catch (Exception e) {

		}
	}

	public void finalize() {
		try {
			rs.close();
			stmt.close();
			conn.close();
		} catch (Exception e) {

		}
	}
}

class PerClientThread extends Thread {
	Socket s;
	static ArrayList socketArray = new ArrayList();
	static DBConnect dbc;
	
	public PerClientThread()
	{
		
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub

		socketArray.add(s);
		BufferedReader br;

		
		try {
			br = new BufferedReader(new InputStreamReader(s.getInputStream()));
			String temp;
			while ((temp = br.readLine()) != null) {
				// DB Query
				if (temp.startsWith("select")) {
					
					try {
						dbc.rs = dbc.stmt.executeQuery("SELECT * FROM [dbo].[TESTDB]");

						while (dbc.rs.next()) {
							String field1 = dbc.rs.getString("Date");
							String field2 = dbc.rs.getString("FileName");
							System.out.println(field1);
							System.out.println(field2);

							java.sql.Blob blb = dbc.rs.getBlob("Image");
							byte[] imagebytes = blb.getBytes(0, (int) blb.length());
							BufferedImage theImage = ImageIO.read(new ByteArrayInputStream(imagebytes));

						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					temp = "SQL:" + temp;
					System.out.println(temp);
				}
				// Arduino
				else if (temp.startsWith("insert"))
				{
					
				}
				// Arduino
				else if (temp.startsWith("image"))
				{

			        int size = Integer.parseInt(br.readLine());
			        
			        DataInputStream inputStream = new DataInputStream(s.getInputStream());
			        
			        byte[] imageAr = new byte[size];
			        inputStream.read(imageAr, 0, size);

			        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));

			        System.out.println("Received " + image.getHeight() + "x" + image.getWidth() + ": " + System.currentTimeMillis());
			        ImageIO.write(image, "png", new File("C:\\test2.png"));


				}
				// Arduino
				else if (temp.startsWith("to"))
				{
					
				}
				System.out.print(s.getInetAddress() + " : ");
				System.out.println(temp);
				for (int i = 0; i < socketArray.size(); i++) {
					PrintWriter os = new PrintWriter(socketArray.get(i).getOutputStream(), true);
					os.print(s.getInetAddress() + " : ");
					os.println(temp);
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.run();
	}
}

public class Server {
	public static void main(String[] args) throws Exception {
 
		System.out.println("Server Side");
		ServerSocket ss = new ServerSocket(33333);
		Socket s;
		while (true) {
			s = ss.accept();
			PerClientThread pct = new PerClientThread();
			pct.s = s;
			pct.dbc = new DBConnect();
			pct.start();
		}

	}
}










Client.java
package com.tistory.tansanc;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;

class MyFrame extends JFrame {
	public static JTextArea textArea;
	JTextField textField;
	PrintWriter out;
	Socket s;

	public MyFrame() {
		textArea = new JTextArea();
		textField = new JTextField();
		add(BorderLayout.CENTER, textArea);
		add(BorderLayout.SOUTH, textField);
		textField.addActionListener(new FieldListener());
		setSize(300, 200);
		setTitle("채팅프로그램 Client");
		setVisible(true);
		// GUI를 설계한다.
	}

	class FieldListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			if (textField.getText().compareTo("image") == 0) {

				BufferedImage image;
				ByteArrayOutputStream byteArrayOutputStream = null;
				DataOutputStream os = null;
				try {
					image = ImageIO.read(new File("C:\\test.png"));
					byteArrayOutputStream = new ByteArrayOutputStream();
					ImageIO.write(image, "png", byteArrayOutputStream);
					os = new DataOutputStream(s.getOutputStream());
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				try {
					int size = byteArrayOutputStream.size();
					out.println("image");
					out.println(size);
					os.write(byteArrayOutputStream.toByteArray());
					os.flush();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			} else {
				out.println(textField.getText());
				textField.setText("");
			}
			// 메세지 보내기
		}
	}
}

class SendThread extends Thread {
	PrintWriter out;

	public SendThread(PrintWriter out) {
		this.out = out;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
	}
}

class RecvThread extends Thread {
	BufferedReader in;

	public RecvThread(BufferedReader in) {
		this.in = in;
	}

	@Override
	public void run() {
		String temp;
		try {
			while ((temp = in.readLine()) != null) {

				MyFrame.textArea.setText(MyFrame.textArea.getText() + "\n" + temp);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class ClientModule {
	MyFrame mFrame;
	SendThread mSendThread;
	RecvThread mRecvThread;
	Socket s;

	// 서버에 패킷을 보내는 Thread
	// 서버로부터 패킷을 받는 Thread
	public ClientModule() // 준비
	{

		try {
			s = new Socket("192.168.10.17", 33333);
			PrintWriter out = new PrintWriter(s.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			mFrame = new MyFrame(); // GUI 객체
			mFrame.s = s;
			mFrame.out = out;
			mSendThread = new SendThread(out);
			mRecvThread = new RecvThread(in);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	void start() // 시작
	{
		mSendThread.start();
		mRecvThread.start();
	}
}

public class Client {
	public static void main(String[] args) {
		ClientModule cm = new ClientModule();
		// 초기화 작업
		cm.start();
		// Thread.start();
	}
}





JAVA 데이터베이스 실습 예제 UI

Programming/JAVA,JSP 2013. 2. 24. 12:51 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.awt.BorderLayout;

import java.awt.GridLayout;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JList;

import javax.swing.JPanel;


class UI extends JFrame{

    JPanel panel1;

    JPanel panel2;

    JPanel panel3;

    JPanel panel4;

    JList list1;

    JList list2;

    JList list3;

    JList list4;

    JButton updateButton;

   

    public UI()

    {

        JLabel label1 = new JLabel("book_id");

        JLabel label2 = new JLabel("title");

        JLabel label3 = new JLabel("publi");

        JLabel label4 = new JLabel("price");

        String[] listItem1 = { "green", "red", "orange", "dark blue" };

        String[] listItem2 = { "green", "red", "orange", "dark blue" };

        String[] listItem3 = { "green", "red", "orange", "dark blue" };

        String[] listItem4 = { "green", "red", "orange", "dark blue" };

        list1 = new JList(listItem1);

        list2 = new JList(listItem2);

        list3 = new JList(listItem3);

        list4 = new JList(listItem4);

        updateButton = new JButton("Update");

        panel1 = new JPanel(new BorderLayout());

        panel2 = new JPanel(new BorderLayout());

        panel3 = new JPanel(new BorderLayout());

        panel4 = new JPanel(new BorderLayout());

       

        setSize(600,400);

        setVisible(true);

        setLayout(new GridLayout(0, 5));

        add(panel1);

        add(panel2);

        add(panel3);

        add(panel4);

        add(updateButton);

        panel1.add(label1,BorderLayout.NORTH);

        panel2.add(label2,BorderLayout.NORTH);

        panel3.add(label3,BorderLayout.NORTH);

        panel4.add(label4,BorderLayout.NORTH);

        panel1.add(list1,BorderLayout.CENTER);

        panel2.add(list2,BorderLayout.CENTER);

        panel3.add(list3,BorderLayout.CENTER);

        panel4.add(list4,BorderLayout.CENTER);

    }

   

}

public class Test {

       public static Connection makeConnection()

       {

             String url = "jdbc:mysql://localhost/book_db";

             String id = "root";

             String password = "green";

             Connection con = null;

             try {

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

                    System.out.println("드라이버 적재 성공");

                    con = DriverManager.getConnection(url, id, password);

                    System.out.println("데이터베이스 연결 성공");

             } catch (ClassNotFoundException e) {

                    System.out.println("드라이버를 찾을 없습니다.");

             } catch (SQLException e) {

                    System.out.println("연결에 실패하였습니다.");

             }

             return con;

       }

       public static void main(String arg[]) throws SQLException {

           UI ui = new UI();

           Connection con = makeConnection();

           Statement stmt = con.createStatement();

           ResultSet rs = stmt.executeQuery("SELECT * FROM books");

           while (rs.next()) {

                  int id = rs.getInt("book_id");

                  String title = rs.getString("title");

                  System.out.println(id + " " + title);

           }

       }

}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA JTABLE 사용 예제  (0) 2013.03.03
JAVA executeQuery INSERT DELETE  (0) 2013.03.02
JAVA JDBC 튜토리얼 예제 사이트  (0) 2013.02.24
JAVA 채팅 프로그램 + GUI  (0) 2013.02.23
RadioButton exam  (0) 2013.02.03