Insert into mysql - Java JDBC

Java examples for JDBC:MySQL

Description

Insert into mysql

Demo Code

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    try {// w w  w .  j a v a 2s .  co m
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Connection formed successfully");
        String myUrl = "jdbc:mysql://localhost/mydb";
        String pwd = "arijit";
        Connection con = DriverManager
                .getConnection(myUrl, "root", pwd);
        Statement st = con.createStatement();
        String insertQuery = "INSERT INTO insert_tab values(?,?,?)";
        String field1 = jTextField1.getText();
        String field2 = jTextField2.getText();
        String field3 = jTextField3.getText();
        PreparedStatement ps = null;
        ps = con.prepareStatement(insertQuery);
        ps.setString(1, field1);
        ps.setString(2, field2);
        ps.setString(3, field3);
        long timeNow = System.nanoTime();
        ps.execute();
        long timeAfter = System.nanoTime() - timeNow;
        jTextField4.setText("" + timeAfter);
        st.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Related Tutorials