본문 바로가기

IT&코딩/국비지원

JDBC

728x90
반응형

■ 1

 

package javapkg1;

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

public class Connect100 {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		
		// 자바 - DB 연동 : JDBC
		// 연동을 위해 ojdbc8.jar가 필요.
		
		// 프로젝트-마우스우클릭 - build path - configure build path
		// - library 탭 - classPath - add external jar
		// ojdbc8.jar를 선택한 후 apply and close
		// 결과로 referenced libraries 안에서 ojdbc8.jar 파일 확인
		
		// 이 방법은 프로젝트마다 jar 파일을 넣어야 한다.
		// (즉, jar 파일을 jdk 안에 넣을 수도 있다.)
		
		// DB와 접속해보자
		Connection con = null; // 접속객체
		
		// 드라이버 메모리 로딩
		// 클래스명.스태틱메소드()
		Class.forName("oracle.jdbc.driver.OracleDriver");
		// ㄴ ojdbc8.jar 안에 oracle.jdbc.driver 패키지 안에
		// ㄴ OracleDriver.class를 메모리에 로딩
		
		// url 사용하여 접속
		// 클래스명.스태틱메소드()
		con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:" // 내 자신한테 접속
				+ "1521:xe", "hr", "hr");
		
		System.out.println("접속성공!");
	}

}

 

■ 2

 

package javapkg1;

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

public class Connect101 {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {

		Connection con1 = null; // 접속객체

		Class.forName("oracle.jdbc.driver.OracleDriver");
		
		con1 = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:" // 내 자신한테 접속
				+ "1521:xe", "hr", "hr");
				
		System.out.println("접속성공!");
		System.out.println("이제 사원명단 전체 검색");
		
		Scanner sc1 = new Scanner(System.in);
		System.out.print("검색할 사원의 이름은 : ");
		String irum = sc1.next();
		
		String sql2 = "select * from employees" 
				+ " where first_name = '" + irum + "'"; // 여기는 그냥 java 문장
		
		// 그러므로 java 문장이 sql 문장이 되려면
		Statement st2 = con1.createStatement(); // import java.sql...
		ResultSet rs2 = st2.executeQuery(sql2); // executeQuery : 조회를 해라. 
		// rs2 가 가리키는 종이박스에 실행결과가 다 들어간다.
		
		while(rs2.next()) {
			
			int id = rs2.getInt("employee_id"); // 컬럼명, 순번, alias
			// rs2.getInt(1); 도 가능
			String fname = rs2.getString("first_name");
			int salary = rs2.getInt("salary"); // rs2.getInt(18); 도 가능
			int d_id = rs2.getInt("department_id");
			String email = rs2.getString("email");
			String l_name = rs2.getString("last_name");
			String h_date = rs2.getString("hire_date");
			String h2_date = h_date.substring(0, 10); // 시간을 제거하기 위해 
			
			// 나는 몇번째 row에서 진행중인지 알고 싶다. 일련번호 찍기
			System.out.println(rs2.getRow() + "\t" + id + "\t"
					+ h2_date + "\t" + fname + "\t" + salary + "\t"
					+ d_id + "\t" + email + "\t" + l_name);
			// 2006-05-23 00:00:00 => db에서 보면 06/05/23
		}
		
		con1.close();
		System.out.println("접속끝");
		
	}

}

 

■ 3

 

package javapkg3;

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.util.Scanner;

public class Connection104 {

	public static void main(String[] args) throws SQLException, ClassNotFoundException {
		
		Connection con1 = null; // 접속객체
		Class.forName("oracle.jdbc.driver.OracleDriver");
		
		con1 = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:" // 내 자신한테 접속
				+ "1521:xe", "hr", "hr");
						
		System.out.println("접속성공!");
		System.out.println("이제 사원명단 전체 검색");
		
		Scanner sc1 = new Scanner(System.in);

		System.out.println("검색 급여 기준 : ");
		
		int sal2 = sc1.nextInt();
		
		String sql2 = "select first_name 이름, salary 봉급"
				+ " from employees"
				+ " where salary >= ?";
		// ?로 대체
		
		PreparedStatement ps2 = con1.prepareStatement(sql2); // sql2 o
		// 클래스					// 접속객체.메소드()
		
		// ?를 채워야 한다.
		
		ps2.setInt(1, sal2);
		
		ResultSet rs2 = ps2.executeQuery(); // sql2 x
				
		while(rs2.next()) {
					
			String fname = rs2.getString("이름"); // alias를 사용할 거면 써먹어야 한다.
			// 만약 써놓고 사용하지 않으면 에러
			int salary = rs2.getInt("봉급");		
			System.out.println(rs2.getRow() + "\t" + fname + "\t" + salary);
		}
				
		con1.close();
		System.out.println("접속끝");

	}

}

 

■ 4 - GUI 연동

 

package javapkg7;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class ChangeNameGui extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField txtDisplay;

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

	/**
	 * Create the frame.
	 */
	public ChangeNameGui() {
		setForeground(Color.GREEN);
		setTitle("\uB0B4\uAC00\uB9CC\uB4E0 \uC5C5\uB370\uC774\uD2B8 GUI");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 919, 395);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("\uBCC0\uACBD\uD560\uC774\uB984");
		lblNewLabel.setForeground(Color.BLUE);
		lblNewLabel.setFont(new Font("맑은 고딕", Font.BOLD, 15));
		lblNewLabel.setBounds(48, 40, 160, 29);
		contentPane.add(lblNewLabel);
		
		textField = new JTextField();
		textField.setBackground(Color.YELLOW);
		textField.setForeground(Color.RED);
		textField.setFont(new Font("맑은 고딕", Font.BOLD, 15));
		textField.setBounds(246, 35, 253, 34);
		contentPane.add(textField);
		textField.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("\uBCC0\uACBD\uB420\uC774\uB984");
		lblNewLabel_1.setForeground(Color.BLUE);
		lblNewLabel_1.setFont(new Font("맑은 고딕", Font.BOLD, 15));
		lblNewLabel_1.setBounds(48, 82, 160, 42);
		contentPane.add(lblNewLabel_1);
		
		textField_1 = new JTextField();
		textField_1.setForeground(Color.RED);
		textField_1.setBackground(Color.YELLOW);
		textField_1.setFont(new Font("맑은 고딕", Font.BOLD, 15));
		textField_1.setBounds(246, 79, 253, 34);
		contentPane.add(textField_1);
		textField_1.setColumns(10);
		
		JButton btnNewButton = new JButton("\uC774\uB984 \uC5C5\uB370\uC774\uD2B8");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//여기다가 도스소스 복사해서 붙여
				Connection con1=null;
			 	
				
				try {
					Class.forName ("oracle.jdbc.driver.OracleDriver");
				} catch (ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			 	
		 		try {
					con1 = DriverManager.getConnection //db접속
					   ("jdbc:oracle:thin:@127.0.0.1:"
					    + "1521:xe", "hr","hr");
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

		      //("jdbc:oracle:thin:@127.0.0.1:1521:xe", "hr","hr");
		 System.out.println("접속했다고 전해라");
		 
		 /*create table jdbc_tab3(
				   sawon_id    number(10),
				   sawon_name  varchar2(20),
				   sawon_sal   number(10),
				   sawon_jik   varchar2(20) 
				);

		insert into jdbc_tab3 
				values (1,'홍길동',3700000,'대리');
		*/

		 String sql2 =
		 "update jdbc_tab3 " +
		 "set sawon_name= ? " +
		 "where sawon_name = ? ";
		 
		 PreparedStatement pst1=null;////////////////
		try {
			pst1 = con1.prepareStatement(sql2);
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		/* Scanner sc1=new Scanner(System.in);
		 
		 System.out.print("변경할이름: ");
		 String hal_name=sc1.next();
		 
		 System.out.print("변경될이름: ");
		 String deul_name=sc1.next();*/
		 
		 
		 try {
			pst1.setString(1, textField_1.getText());//텍스트필드에 있는 변경될 이름 
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		 //pst1.setString(1, deul_name);
		 
		 try {
			pst1.setString(2,textField.getText()) ;//텍스트필드에 있는 변경할 이름 
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		 //pst1.setString(2, hal_name);
		 
		   
		 int rowcnt1=0;////////////////
		try {
			rowcnt1 = pst1.executeUpdate();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}//////
		 if(rowcnt1 >=1) {
		    txtDisplay.setText("update ok !!!");
		    System.out.println(rowcnt1+"행 update");//update 행 갯수
		 }
		 else {
			   txtDisplay.setText("update error !!!");
			    System.out.println("update error");	 
			 
		 }
			 
		try {
			con1.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}//////////////////////
		System.out.println("접속끝");	//////////////

			}
		});
		btnNewButton.setBackground(Color.GREEN);
		btnNewButton.setForeground(Color.MAGENTA);
		btnNewButton.setFont(new Font("맑은 고딕", Font.BOLD, 15));
		btnNewButton.setBounds(270, 199, 160, 42);
		contentPane.add(btnNewButton);
		
		txtDisplay = new JTextField();
		txtDisplay.setFont(new Font("굴림", Font.BOLD, 18));
		txtDisplay.setBounds(114, 266, 462, 51);
		contentPane.add(txtDisplay);
		txtDisplay.setColumns(10);
	}
}
728x90
반응형

'IT&코딩 > 국비지원' 카테고리의 다른 글

리눅스 - 3 (tera term 사용)  (0) 2023.08.17
리눅스 - 1 (centos, 설치)  (0) 2023.08.16
스프링 - 2  (1) 2023.07.12
형상관리  (0) 2023.07.10
스프링 - 1  (0) 2023.06.20