Java Insert JTable Rows Data Into MySQL complete code solution

Java Insert JTable Rows Data Into MySQL

Project Source Code:

// function to get the connection

    public Connection getConnection()

    {

         try {

            Class.forName(“com.mysql.jdbc.Driver”);

        } catch (ClassNotFoundException ex) {

             System.out.println(ex.getMessage());

        }

        

        Connection con = null;

        

        try {

            con = DriverManager.getConnection(“jdbc:mysql://localhost/s_t_d”, “root”, “”);

        } catch (SQLException ex) {

            System.out.println(ex.getMessage());

        }

        return con;

    } 

// insert button

    private void jButtonInsertActionPerformed(java.awt.event.ActionEvent evt) {                                              

        

        Connection con = getConnection();

        Statement st;

        

        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

        

        try {

            st = con.createStatement();

            

            for(int i = 0; i < model.getRowCount(); i++){

                

                int id = Integer.valueOf(model.getValueAt(i, 0).toString());

                String fn = model.getValueAt(i, 1).toString();

                String adr = model.getValueAt(i, 2).toString();

                String bdate = model.getValueAt(i, 3).toString();

                

                String sqlQuery = “INSERT INTO `student`(`Id`, `FullName`, `Address`, `BirthDate`) VALUES (“+id+”,'”+fn+”‘,'”+adr+”‘,'”+bdate+”‘)”;

                

                st.addBatch(sqlQuery);

            }

            

            int[] rowsInserted = st.executeBatch();

            System.out.println(“Data Inserted”);

            System.out.println(“rowsInserted Count = ” + rowsInserted.length);

            

        } catch (SQLException ex) {

            Logger.getLogger(Insert_All_JTable_Row_Into_MySQL.class.getName()).log(Level.SEVERE, null, ex);

        }

        

    }

OutPut:

java add jtable data to mysql

freshersonline

Also read : Starlink should be fully mobile by the end of 2021
Also read : Can I invest in Cryptocurrency?

freshersonline

Java Insert JTable Rows Data Into MySQL
#Java #Insert #JTable #Rows #Data #MySQL

Leave a Comment