18 April 2016

Swing database connection insert delete update Eclipse. How to add library connect to database


Database mysql Workbench

MySQL error code: 1175 during UPDATE in MySQL Workbench

   

Follow the steps below before executing the UPDATE command: On MysqlWorkbench
  1. Go to Edit --> Preferences
  2. Click "SQL Queries" tab and uncheck "Safe Updates" check box
  3. Query --> Reconnect to Server // logout and then login
  4. Now execute your sql query


ConnectionFuntion.java
package Funtion;

import java.net.URI;
import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionFuntion {

 private static Connection conn;

 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost:3306/student";
 static final String USER = "root";
 static final String PASS = "1234567";

 public static Connection getConnection() {

  try {
   Class.forName(JDBC_DRIVER);
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
  } catch (Exception e) {
   System.out.println("Ket noi bi loi!");
  }
  return conn;
 }
}

ManagerLogin .java




package QLUser;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import Funtion.ConnectionFuntion;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;

public class ManagerLogin {

 private Connection conn;
 private ResultSet rs;
 private PreparedStatement stmt;

 private JFrame frame;
 private JTextField txtID;
 private JTextField txtName;
 private JTextField txtClass;
 private JTable tableStudent;

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

 /**
  * Create the application.
  */
 public ManagerLogin() {
  initialize();
  try {
   conn = ConnectionFuntion.getConnection();
  } catch (Exception e) {
   // TODO: handle exception
  }
  showTable();
 }

 public void showTable() {
  Vector cols = new Vector();
  cols.addElement("ID");
  cols.addElement("Name");
  cols.addElement("Gender");
  cols.addElement("Class");

  // tao vector du lieu
  Vector data = new Vector();
  String sql = "SELECT * FROM student.student";
  try {
   stmt = conn.prepareStatement(sql);
   rs = stmt.executeQuery();
   while (rs.next()) {
    Vector student = new Vector();
    student.addElement(rs.getInt("id"));
    student.addElement(rs.getString("name"));
    student.addElement(rs.getString("gender"));
    student.addElement(rs.getString("Class"));

    data.add(student);
   }
  } catch (Exception e) {
   // TODO: handle exception
  }
  tableStudent.setModel(new DefaultTableModel(data, cols));
 }

 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frame = new JFrame();
  frame.setBounds(100, 100, 450, 413);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  JMenuBar menuBar = new JMenuBar();
  frame.setJMenuBar(menuBar);

  JMenu mnFile = new JMenu("File");
  menuBar.add(mnFile);

  JMenuItem mntmSave = new JMenuItem("Save");
  mntmSave.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing001\\icon\\Save-icon.png"));
  mnFile.add(mntmSave);

  JSeparator separator = new JSeparator();
  mnFile.add(separator);

  JMenuItem mntmExit = new JMenuItem("Exit");
  mntmExit.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    System.exit(0);
   }
  });
  mntmExit.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing001\\icon\\Actions-window-close-icon.png"));
  mnFile.add(mntmExit);

  JMenu mnEdit = new JMenu("Edit");
  menuBar.add(mnEdit);

  JMenu mnAbout = new JMenu("About");
  menuBar.add(mnAbout);
  frame.getContentPane().setLayout(null);

  txtID = new JTextField();
  txtID.setBounds(87, 23, 86, 20);
  frame.getContentPane().add(txtID);
  txtID.setColumns(10);

  JLabel lblId = new JLabel("ID:");
  lblId.setBounds(20, 26, 46, 14);
  frame.getContentPane().add(lblId);

  JLabel lblName = new JLabel("Name");
  lblName.setBounds(20, 57, 46, 14);
  frame.getContentPane().add(lblName);

  JLabel lblClass = new JLabel("Class");
  lblClass.setBounds(20, 90, 46, 14);
  frame.getContentPane().add(lblClass);

  txtName = new JTextField();
  txtName.setBounds(87, 54, 86, 20);
  frame.getContentPane().add(txtName);
  txtName.setColumns(10);

  txtClass = new JTextField();
  txtClass.setBounds(87, 90, 86, 20);
  frame.getContentPane().add(txtClass);
  txtClass.setColumns(10);

  JComboBox comboBox = new JComboBox();
  comboBox.setModel(new DefaultComboBoxModel(new String[] { "Female", "Male" }));
  comboBox.setBounds(87, 131, 86, 20);
  frame.getContentPane().add(comboBox);

  JLabel lblGender = new JLabel("Gender");
  lblGender.setBounds(20, 134, 46, 14);
  frame.getContentPane().add(lblGender);

  JButton btnAdd = new JButton("Add");
  btnAdd.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing001\\icon\\add-icon.png"));
  btnAdd.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {

    String sql = "INSERT INTO student.student (id, name, gender, class) VALUES (?, ?, ?, ?)";

    try {
     stmt = conn.prepareStatement(sql);
     // set gia tri bien
     stmt.setString(1, txtID.getText());
     stmt.setString(2, txtName.getText());
     stmt.setString(3, (String) comboBox.getSelectedItem());
     stmt.setString(4, txtClass.getText());

     // Thuc hien cho cac cau lenh nhu: Update, delete, insert
     stmt.executeUpdate();
    } catch (SQLException e1) {
     // TODO Auto-generated catch block
     JOptionPane.showMessageDialog(null, "Vui long nhap lai");
    }
    showTable();
   }
  });
  btnAdd.setBounds(256, 22, 115, 23);
  frame.getContentPane().add(btnAdd);

  JButton btnDelete = new JButton("Delete");
  btnDelete.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing001\\icon\\Actions-edit-delete-icon.png"));
  btnDelete.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String sql = "DELETE FROM student.student WHERE id=?";
    int choice = JOptionPane.showConfirmDialog(null, "Are you sure?");
    if (choice == JOptionPane.YES_OPTION) {

     try {
      int id = Integer.parseInt(txtID.getText());
      stmt = conn.prepareStatement(sql);
      stmt.setInt(1, id);
      stmt.executeUpdate();
     } catch (Exception e2) {
      JOptionPane.showMessageDialog(null, "Hay chon ten khac");
     }
    }
    showTable();
   }
  });
  btnDelete.setBounds(256, 86, 115, 23);
  frame.getContentPane().add(btnDelete);

  JButton btnExit = new JButton("Exit");
  btnExit.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing001\\icon\\Actions-window-close-icon.png"));
  btnExit.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    System.exit(0);
   }
  });
  btnExit.setBounds(256, 120, 115, 23);
  frame.getContentPane().add(btnExit);

  JScrollPane scrollPane = new JScrollPane();
  scrollPane.setBounds(20, 180, 404, 152);
  frame.getContentPane().add(scrollPane);

  tableStudent = new JTable();
  scrollPane.setViewportView(tableStudent);
  tableStudent.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent e) {
    int row = tableStudent.getSelectedRow();
    if (row != -1) {
     txtID.setText(tableStudent.getValueAt(row, 0).toString());
     txtName.setText(tableStudent.getValueAt(row, 1).toString());
     txtClass.setText(tableStudent.getValueAt(row, 3).toString());
     comboBox.setSelectedItem(tableStudent.getValueAt(row, 2).toString());

    }
   }
  });

  JButton btnUpdate = new JButton("Update");
  btnUpdate.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing001\\icon\\Actions-edit-redo-icon.png"));
  btnUpdate.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    String sql = "UPDATE student.student SET name=?, gender=?, class=? WHERE id=?";

    try {
     int id = Integer.parseInt(txtID.getText());
     stmt = conn.prepareStatement(sql);
     // set gia tri bien
     stmt.setString(1, txtName.getText());
     stmt.setString(2, comboBox.getSelectedItem().toString());
     stmt.setString(3, txtClass.getText());
     stmt.setInt(4, id);

     // Thuc hien cho cac cau lenh nhu: Update, delete, insert
     stmt.executeUpdate();
    } catch (Exception e) {
     JOptionPane.showMessageDialog(null, "Hay chon ten truoc khi update");
    }
    showTable();

   }

  });
  btnUpdate.setBounds(256, 56, 115, 23);
  frame.getContentPane().add(btnUpdate);

 }

}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang