> Java > java지도 시간 > 본문

데이터베이스에 대한 Java 쿼리 및 업데이트 작업에 대한 자세한 설명

怪我咯
풀어 주다: 2017-07-02 10:24:51
원래의
2747명이 탐색했습니다.

이 글에서는 주로 Java를 사용하여 데이터베이스에 대한 기본 쿼리 및 업데이트 작업을 수행하는 방법을 소개합니다. Java 시작하기에 대한 기본 지식입니다. 필요한 친구는

Database Query

사용하기를 참조하세요. Connection 객체의 메소드Statement 객체를 생성하고,Statement 객체의 excuteQuery() 메소드를 이용하여 SQL 쿼리 문을 실행하고, 결과 세트를 반환한 후, getXXX()와 같은 메소드를 이용하여 결과 세트의 데이터를 읽어옵니다. 이러한 일련의 단계를 거쳐 데이터베이스에 대한 쿼리가 실현될 수 있습니다.

【예시】Java 애플리케이션이 데이터베이스에 액세스합니다. 애플리케이션은 후보자 정보 테이블 ksInfo를 열고 후보자에 대한 다양한 정보를 검색합니다. 후보자 정보 데이터베이스의 구조는 다음과 같다고 가정하자.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.sql.*;
public class Example10_9 extends JFrame implements ActionListener{
  public static Connection connectByJdbcodbc(String url, String username,String password){
    Connection con = null;
    try{
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //加载ODBC驱动程序
    }
    catch (Exception e){
      e.printStackTrace();
      return null; //加载失败,连接不成功
    }
    try{
      con = DriverManager.getConnection(url, username, password);
    }
    catch (SQLException e){
      e.printStackTrace();
      return null; //连接失败
    }
    return con; //连接成功
  }
  String title[] ={"考号", "姓名", "成绩", "地址", "简历"};
  JTextField txtNo = new JTextField(8);
  JTextField txtName = new JTextField(10);
  JTextField txtScore = new JTextField(3);
  JTextField txtAddr = new JTextField(30);
  JTextArea txtresume = new JTextArea();
  JButton prev = new JButton("前一个");
  JButton next = new JButton("后一个");
  JButton first = new JButton("第一个");
  JButton last = new JButton("最后一个");
  Statement sql; //SQL语句对象
  ResultSet rs; //存放查询结果对象
  Example10_9(Connection connect){
    super("考生信息查看窗口");
    setSize(450, 350);
    try{
      sql = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
      rs = sql.executeQuery("SELECT * FROM ksInfo");
      Container 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(txtName);
      p[2].add(txtScore);
      p[3].add(txtAddr);
      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 = new 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(next);
      p3.add(first);
      p3.add(last);
      prev.addActionListener(this);
      next.addActionListener(this);
      first.addActionListener(this);
      last.addActionlistener(this);
      rs.first();
      readRecord();
    }
    catch (Exception e){
      e.printStackTrace():
    }
    setVisible(ture);
  }
  public void modifyRecord(Connection connect){
    String stuNo = (String)JOptionPane.showInputDialog(null,
      "请输入考生考号", "输入考号对话框", JOptionPane.PLAIN_MESSAGE, null,
      null, "");
    try {
      sql = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
      rs = sql.executeQuery("SELECT * FROM ksInfo");
      Container con = 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[1].add(txtName);
      p[2].add(txtScore);
      p[3].add(txtAddr);
      Jpanel p1 = new Jpane(new GridLayout(4, 1, 0, 8));
      JScrollPane jsp = new JScrollPane(txtResume,
        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
      jsp.setPreferredSize (new dimension(300, 60));
      for (int i = 0; i < 4; i++){
        p1.add(p[i]);
      }
      Jpanel p2 = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
      p2.add(new JLableI(title[4]));
      p2.add(jsp);
      JPanel p3 = new JPanel();
      p3.add(prev);
      p3.add(next);
      p3.add(first);
      p3.add(last);
      prev.addActionListener(this);
      next.addActionListener(this);
      first.addActionListenerIthis);
      last.addActionListener(this);
      rs.first();
      readRecord();
    }
    catch (Exception e){
      e.printStackTrace();
    }
    setVisible(true);
  }
  boolean readRecord(){
    try{
      txtNo.setText(rs.getString("考号")); txtName.setText(rs.getString("姓名")); txtScore.setText(rs.getString("成绩"));
      txtAddr.setText(rs.getString("地址")); txtResume.setText(rs.getString("简历"));
    }
    catch (SQLException e){
      e.printStackTrace(); return false;
    }
    return true;
  }
  public void actionPerformed(ActionEvent e){
    try{
      if (e.getSource() == prev)rs.previous();
      else if (e.getSource() == next)rs.next();
      else if (e.getSource() == first)rs.first();
      else if (e.getSource() == last)rs.last(); readRecord();
    }
    catch (Exception e2){}
  }
  public static void main(String args[]){
    connection connect = null;
    JFrame .setDefaultLookAndFeeDecorated(true);
    Font font = 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 데이터베이스 업데이트
데이터베이스 업데이트 작업에는 데이터 테이블 생성, 삭제 및 데이터 테이블 레코드 추가, 삭제, 수정 등의 작업이 포함됩니다. . 데이터 SQL 명령을 사용하여 구현된 경우 SQL 업데이트 문을 실행하여 데이터 테이블을 수정하기 위해 SQL 업데이트 문을 실행하고, 데이터 테이블 레코드를 추가하려면 SQL 삽입 문을 실행합니다.

예를 들어 이전 데이터 쿼리 예제를 기반으로 데이터 테이블에 수정 및 삽입을 추가합니다. 공간의 제약으로 인해 완전한 프로그램은 제공되지 않으며 수정 및 삽입을 구현하는 방법만 제공됩니다. 프로그램은 기존 탐색을 통해 데이터 테이블의 특정 위치를 찾고 카벙클 레코드를 편집, 수정, 삽입 또는 삭제한 후 저장 버튼을 눌러 수정된 데이터 테이블을 완료할 수 있습니다. . 구하다.

다음 코드는 데이터 테이블을 업데이트하는 방법을 설명합니다. 데이터 테이블에 연결할 때 얻은 ResultSet 객체가 업데이트 가능함을 지정해야 합니다.

아아아아

위 내용은 데이터베이스에 대한 Java 쿼리 및 업데이트 작업에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!