데이터베이스 쿼리
Connection 객체의 createStatement 메소드를 사용하여 Statement 객체를 생성하고, State 객체의 excuteQuery() 메소드를 사용하여 SQL 쿼리문을 실행하고 결과 set을 반환한 후, 다음과 같은 메소드를 사용하여 결과 set에서 데이터를 읽어온다. getXXX(). 이러한 일련의 단계를 거쳐 데이터베이스에 대한 쿼리가 실현될 수 있습니다.
[예제] Java 애플리케이션이 데이터베이스에 액세스합니다. 애플리케이션은 후보자 정보 테이블 ksInfo를 열고 후보자에 대한 다양한 정보를 검색합니다. 후보자 정보 데이터베이스의 구조는 다음과 같다고 가정한다.
import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;import java.sql.*;public class example10_9 확장 JFrame 구현 ActionListener{ public static Connection connectByJdbcodbc( 문자열 URL, 문자열 사용자 이름, 문자열 비밀번호){ 연결 con = null try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //ODBC 드라이버 로드} catch (Exception e){ e.printStackTrace() return null //로드 실패, 연결 실패} try{ con = DriverManager .getConnection(url, 사용자 이름, 비밀번호); } catch(SQLException e){ e.printStackTrace(); return null //연결 실패} return con; String title[] ={"시험 번호", "이름", "학년", "주소", "이력서"}; JTextField txtNo = new JTextField(8) txtName = new JTextField(10); JTextField(3); JTextField txtAddr = 새로운 JTextField(30); JTextArea txtresume = new JButton prev = new JButton("이전"); JButton next = new JButton("next"); JButton first = new JButton("first"); ); 명령문 sql; //SQL 명령문 객체 ResultSet rs; //스토리지 쿼리 결과 objectExample10_9(Connection connect){ super("후보 정보 보기 창"); setSize(450, 350); try{ sql = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY) rs = sql. ("SELECT * FROM ksInfo"); 컨테이너 con = getContentPane(); con.setLayout(new BorderLayout(0, 6); JPanel p[] = new JPanel[4]; for (int i = 0; i < 4; i++){ p[ i] = new JPane(new FlowLayout(FlowLayout.LEFT, 8, 0)) p[i].add(new JLabel(title[i])); p[0].add(txtNo); p[1].add(txtScore); JPanel p1 = new JPane(new GridLayout94, 1, 0, 8)); JScrollPane jsp = new JScrollPane(txtResume, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jsp.setPreforredSize(new Dimension(300, 60); for (int i = 0; i < 4; i++){ p1.add(p[i]); } JPanel p2 = 신규 JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0); p2.add(new JLabel(title[4])); p2.add(jsp); Jpanel p3 = new Jpanel(); p3.add(prev); p3.add(다음); p3.add(first); prev.addActionListener(this); next.addActionListener(this); last.addActionlistener(this); readRecord() } catch (Exception e){ e.printStackTrace(): } setVisible(ture); } 공개 무효 수정 기록(연결 연결){ 문자열 stuNo = (문자열)JOptionPane.showInputDialog(null, "응시자의 시험 번호를 입력하십시오", "시험 번호 입력 대화 상자", JOptionPane.PLAIN_MESSAGE, null, null, "") try { sql = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); .executeQuery("SELECT * FROM ksInfo"); getContentPane(); con.setLayout(new Boarderlayout(0, 6)); Jpanel p[] = new JPanel[4] for (int i = 0; i < ; i++){ p[i] = new JPane(new FlowLayout(flowLayout.LEFT, 8, 0)); p[i].add(new JLabel(title[i])); p[0].add(txtNo); p[2].add(txtScore); Jpanel p1 = new GridLayout(4 , 1, 0, 8)); JScrollPane jsp = new JScrollPane(txtResume, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jsp.setPreferredSize (새 차원(300, 60)) for (int i = 0; i < 4; i++){ p1.add(p[i]) } Jpanel p2 = 새로운 JPanel(새로운 FlowLayout(FlowLayout.LEFT, 10, 0)); p2.add(new JLableI(title[4])); JPanel p3 = new JPanel(); add(다음); p3.add(first); prev.addActionListener(this); next.addActionListenerIthis); last.addActionListener(); readRecord() } catch (Exception e){ e.printStackTrace() } boolean readRecord(){ try{ txtNo.setText(rs.getString("시험 번호")); txtName.setText(rs.getString("이름")); txtScore.setText(rs.getString("점수")); txtAddr.setText(rs.getString("주소")); "재개")) } catch (SQLException e){ e.printStackTrace() return false; true; } public void actionPerformed(ActionEvent e){ try{ if (e.getSource() == prev)rs.previous(); else if (e.getSource() == next)rs.next(); (e.getSource() == first)rs.first(); else if (e.getSource() == last)rs.last() } catch (Exception e2){} } 공개 static void main(String args[]){ 연결 연결 = null; JFrame .setDefaultLookAndFeeDecorated(true); 글꼴 글꼴 = new Font("JFrame", Font.PLAIN, 14) if ((connect =connectByJdbcOdbc("jdbc:odbc) :redsun", "xia", "1234")) == null){ JOptionPane.showMessageDialog(null, "데이터베이스 연결 실패!"); System.exit ( - 1) } new example10_9(connect);
Java 데이터베이스 업데이트 <br />데이터베이스 업데이트 작업에는 데이터 테이블 생성, 삭제, 데이터 테이블 레코드 추가, 삭제 및 수정이 포함됩니다. 데이터 SQL 명령을 사용하여 구현된 경우 SQL 업데이트 문을 실행하여 데이터 테이블을 수정하려면 SQL 삽입 문을 실행하고 데이터 테이블 레코드를 추가하려면 SQL 업데이트() 메서드를 사용하세요.
예를 들어 이전 데이터 쿼리 예제를 기반으로 데이터 테이블에 수정 및 삽입을 추가합니다. 공간의 제약으로 인해 완전한 프로그램은 제공되지 않으며 수정 및 삽입을 구현하는 방법만 제공됩니다. 프로그램은 기존 탐색을 통해 데이터 테이블의 특정 위치를 찾고 카벙클 레코드를 편집, 수정, 삽입 또는 삭제한 후 저장 버튼을 눌러 수정된 데이터 테이블을 완료할 수 있습니다. . 구하다.
다음 코드는 데이터 테이블을 업데이트하는 방법을 설명합니다. 데이터 테이블에 연결할 때 얻은 ResultSet 객체가 업데이트 가능함을 지정해야 합니다.
stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);