Chia sẻ kiến thức
Bạn có muốn phản ứng với tin nhắn này? Vui lòng đăng ký diễn đàn trong một vài cú nhấp chuột hoặc đăng nhập để tiếp tục.

Chương 8: TRUY XUẤT CSDL

Go down

Chương 8: TRUY XUẤT CSDL Empty Chương 8: TRUY XUẤT CSDL

Bài gửi  Admin Wed Nov 26, 2014 3:47 am

Tạo form Connection:
Tạo các biến toàn cục
Code:

public class form_Connection extends javax.swing.JFrame {
    public String driver = "com.mysql.jdbc.Driver";
    public String address;
    public String port;
    public String database;
    public String URL;
    public String username;
    public String pass;
    public Connection connect;
}

Get text từ TextField gán vào các String
Code:

public form_Connection() {
        initComponents();                    
        address = txt_address.getText();          
        port = txt_port.getText();
        database = txt_database.getText();
        URL="jdbc:mysql://"+address+":"+port+"/"+database;
        username= txt_user.getText();
        char[] password= txt_pass.getPassword();
        pass = new String(password);
    }

Nút Connect:
Code:

try {        
            Class.forName(driver);            
            connect  = DriverManager.getConnection(URL,username,pass);
            form_Connection.this.setVisible(false);
            form_Product product = new form_Product(form_Connection.this.connect);
            product.setLocationRelativeTo(null);
            product.setVisible(true);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Cannot initialize connection!");
        }

Nút Reset:
Code:

txt_address.setText(null);
        txt_port.setText(null);
        txt_database.setText(null);
        txt_user.setText(null);
        txt_pass.setText(null);

Tạo form Product:

Tạo các biến toàn cục
Code:

    public static Connection connection;
    public String sql;
    public Statement st;
    public PreparedStatement pre_st;
    public ResultSet rs;
    public int n = 0;

Gán connection = conn
Code:

public form_Product(Connection conn) {
        initComponents();
        connection = conn;
    }

Nút Next:
Code:

int max;
        int min;
        try{
            String query = "select count(*) from product";
            PreparedStatement pre_st1 = connection.prepareStatement(query);
            rs = pre_st1.executeQuery();
            while(rs.next()){
                max = rs.getInt("count(*)");
                min = max * -1;  
                if(n>=min && n<max){
                    n++;
                    if(n==0) n++;
                }  
            }
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }
        try {
            //
            sql = "select * from product";
            //
            st=connection.createStatement();
            rs = st.executeQuery(sql);
            //
            if(rs.absolute(n)){
                txt_productID.setText(rs.getString(1));
                txt_name.setText(rs.getString(2));
                txt_unit.setText(rs.getString(3));
                txt_price.setText(rs.getString(4));
                txt_quantity.setText(rs.getString(5));
            }
            rs.close();
            st.close();
        }
        catch (SQLException ex) {
                //Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("Error : ..."+ex.getMessage());
        }

Nút Back:
Code:

// TODO add your handling code here:
        int max;
        int min;
        try{
            String query = "select count(*) from product";
            PreparedStatement pre_st1 = connection.prepareStatement(query);
            rs = pre_st1.executeQuery();
            while(rs.next()){
                max = rs.getInt("count(*)");
                min = max * -1;  
                if(n>min && n<=max){
                    n--;
                    if(n==0) n--;
                }  
            }
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }
        try {
            //
            sql = "select * from product";
            //
            st=connection.createStatement();
            rs = st.executeQuery(sql);
            //
            if(rs.absolute(n)){
                txt_productID.setText(rs.getString(1));
                txt_name.setText(rs.getString(2));
                txt_unit.setText(rs.getString(3));
                txt_price.setText(rs.getString(4));
                txt_quantity.setText(rs.getString(5));
            }
            rs.close();
            st.close();
        }
        catch (SQLException ex) {
                //Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("Error : ..."+ex.getMessage());
        }

Nút Add:
Code:

try {
            // TODO add your handling code here:
            sql = "insert into product (id, name, unit, price, quantity) values (?, ?, ?, ?, ?)";
            String id = txt_productID.getText();
            String name = txt_name.getText();
            String unit = txt_unit.getText();
            String price = txt_price.getText();
            String quantity = txt_quantity.getText();
            pre_st = connection.prepareStatement(sql);        
            pre_st.setString(1, id);
            pre_st.setString(2, name);
            pre_st.setString(3, unit);
            pre_st.setString(4, price);
            pre_st.setString(5, quantity);
            pre_st.execute();
            JOptionPane.showMessageDialog(null, "Record added");            
        } catch (SQLException ex) {
            Logger.getLogger(form_Product.class.getName()).log(Level.SEVERE, null, ex);
        }

Nút Modify:
Code:

try {
            // TODO add your handling code here:
            sql = "update product set name = ?, unit = ?, price = ?, quantity = ? where id = ?";
            String id = txt_productID.getText();
            String name = txt_name.getText();
            String unit = txt_unit.getText();
            String price = txt_price.getText();
            String quantity = txt_quantity.getText();
            pre_st = connection.prepareStatement(sql);        
            pre_st.setString(1, name);
            pre_st.setString(2, unit);
            pre_st.setString(3, price);
            pre_st.setString(4, quantity);
            pre_st.setString(5, id);
            pre_st.executeUpdate();
            JOptionPane.showMessageDialog(null, "Record modified");            
        } catch (SQLException ex) {
            Logger.getLogger(form_Product.class.getName()).log(Level.SEVERE, null, ex);
        }

Nút Delete:
Code:

try {
            // TODO add your handling code here:
            sql = "delete from product where id = ?";
            String id = txt_productID.getText();
            pre_st = connection.prepareStatement(sql);        
            pre_st.setString(1, id);
            pre_st.execute();
            JOptionPane.showMessageDialog(null, "Record deleted");
            txt_search_productID.setText(null);
            txt_productID.setText(null);
            txt_name.setText(null);
            txt_unit.setText(null);
            txt_price.setText(null);
            txt_quantity.setText(null);
        } catch (SQLException ex) {
            Logger.getLogger(form_Product.class.getName()).log(Level.SEVERE, null, ex);
        }

Nút Exit:
Code:

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        System.exit(0);
    }

Chỉnh lại hàm main
Code:

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
        * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(form_Product.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(form_Product.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(form_Product.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(form_Product.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new form_Product(connection).setVisible(true);
            }
        });
    }
Admin
Admin
Admin

Tổng số bài gửi : 218
Reputation : 22
Join date : 17/11/2012
Age : 32

https://elcit.forumvi.com

Về Đầu Trang Go down

Về Đầu Trang


 
Permissions in this forum:
Bạn không có quyền trả lời bài viết