-1

I imported JDBC driver successfully into netbeans and tested the mySQL connection...works fine but after executing the query, the table is not updated in mySQL. I'm using a GUI to update these values and i'm getting absolutely no errors at all and i'm using exception handling as well!

//here's my code (updated)

  package DBConn;

  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.SQLException;
  import java.sql.Statement;
  import java.util.logging.Level;
  import java.util.logging.Logger;
  //import java.util.*;

  public class FrameDBTest extends javax.swing.JFrame {

public FrameDBTest() {
    initComponents();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jTextField3 = new javax.swing.JTextField();
    jComboBox1 = new javax.swing.JComboBox();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jTextField4 = new javax.swing.JTextField();
    jLabel6 = new javax.swing.JLabel();
    jButton2 = new javax.swing.JButton();
    jLabel5 = new javax.swing.JLabel();
    jPanel2 = new javax.swing.JPanel();
    jPanel3 = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Tapiwa's FlowNation CARS");
    setResizable(false);

    jPanel1.setBackground(new java.awt.Color(153, 153, 255));

    jTextField1.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
    jTextField1.setName("JID"); // NOI18N
    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    jTextField2.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
    jTextField2.setName("JNAME"); // NOI18N
    jTextField2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2ActionPerformed(evt);
        }
    });

    jTextField3.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
    jTextField3.setName("JDISPLACE"); // NOI18N
    jTextField3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField3ActionPerformed(evt);
        }
    });

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "FL 3", "FL 4", "FL 6", "V6", "V8", "V10", "V12", "V16", "W12", "W16" }));
    jComboBox1.setName("ComboCAR"); // NOI18N
    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jComboBox1ActionPerformed(evt);
        }
    });

    jLabel1.setText("Name");

    jLabel2.setText("ID - INT");

    jLabel3.setText("Displacement - FLOAT");

    jLabel4.setText("Cylinders");

    jButton1.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N
    jButton1.setForeground(new java.awt.Color(102, 102, 102));
    jButton1.setText("SAVE");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jTextField4.setFont(new java.awt.Font("Century Gothic", 0, 18)); // NOI18N
    jTextField4.setName("JNAME"); // NOI18N
    jTextField4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField4ActionPerformed(evt);
        }
    });

    jLabel6.setText("Name");

    jButton2.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N
    jButton2.setForeground(new java.awt.Color(102, 102, 102));
    jButton2.setText("SAVE");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jTextField3)
                        .addComponent(jTextField2)
                        .addComponent(jTextField1)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 361, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel6)
                    .addGap(18, 18, 18)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(24, 24, 24))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(34, 34, 34))))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(35, 35, 35)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)))
            .addGap(28, 28, 28)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel4))
            .addGap(25, 25, 25)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel3))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap())
    );

    jLabel5.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
    jLabel5.setForeground(new java.awt.Color(0, 153, 153));
    jLabel5.setText("FlowNation CARS");

    jPanel2.setBackground(new java.awt.Color(153, 153, 153));

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 947, Short.MAX_VALUE)
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 42, Short.MAX_VALUE)
    );

    jPanel3.setBackground(new java.awt.Color(102, 102, 102));

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 0, Short.MAX_VALUE)
    );
    jPanel3Layout.setVerticalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 22, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGroup(layout.createSequentialGroup()
            .addGap(23, 23, 23)
            .addComponent(jLabel5)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel5)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    pack();
}// </editor-fold>                        

private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
}                                           

@SuppressWarnings("empty-statement")
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    try
    {


        Connection CC = DriverManager.getConnection("jdbc:mysql://localhost/CS","root","carrizo");
        Statement ST = (Statement) CC.createStatement();

        //String newdata;
        ST.execute("INSERT INTO carz VALUES('"+jTextField2.getText()+"',"+jTextField1.getText()+",'"+jComboBox1.getSelectedItem()+"',"+jTextField3.getText()+")");
        //ST.executeUpdate(newdata);
    }

    catch(SQLException e)
    {
        System.out.println(e.getSQLState());
        e.getMessage();
        e.getErrorCode();
        e.printStackTrace();
    }

    finally
    {
        System.out.println("\n\nExecuted...\n"); 
    };

}                                        












 ![mySQL database and table][1]
3
  • Replace your catch block with this catch(SQLException e) { e.printStackTrace(); } Commented Mar 11, 2014 at 11:15
  • Please limit your code to the relevant (non-UI) code. Commented Mar 11, 2014 at 14:25
  • Sorry for that...i'll do just that next time. Commented Mar 12, 2014 at 5:58

4 Answers 4

1

Some notes about your code:

Note you're using Statement.execute(String sql) method which is mainly intended to perform database queries. To execute INSERT/UPDATE/DELETE statements it's recommended the use of Statement.executeUpdate() method instead.

Also note your code is vulnerable to SQL injection attacks. You should take a look to PreparedStatement interface which is a subinterface of Statement and will help you to avoid this. Take a look to Using Prepared Statements trail.

For instance you can refactor your code as follows:

Integer param1 = Integer.valueOf(jTextField2.getText());
Integer param2 = Integer.valueOf(jTextField1.getText());
Object param3 = jComboBox1.getSelectedItem();
Integer param4 = Integer.valueOf(jTextField3.getText());

String sql = "INSERT INTO carz VALUES (?, ?, ?, ?)";
PreparedStatement statement = CC.prepareStatement(sql);
statement.setInt(1, param1);
statement.setInt(2, param1);    
statement.setObject(3, param3);
statement.setInt(4, param4);

int result = statement.executeUpdate();

You might want to take a look to this excelent tutorial as well:


Note code within actionPerformed() method is executed in the Event Dispatch Thread (aka EDT) which is a single thread where Swing components creation/update and event handling take place. Time consuming tasks (like database calls) may block this thread causing your GUI become unresponsive. To avoid this you should use SwingWorker class to perform heavy tasks in a background thread and update Swing components in the EDT.


Empty catch blocks ignoring exceptions are not a good practice at all. You should at least print the stack trace:

catch(SQLException e) {
    e.printStackTrace(); // log the exception is even better 
}

About this comment:

but for those textfields without single quotes...they are actually ints

Maybe JSpinner or JFormattedTextField are a better choice in this case.


Finally but not less important, always follow Java Code Conventions. Variable names start with lower-case and must be meaningful.

Sign up to request clarification or add additional context in comments.

4 Comments

Wow...thanx...learnt a lot...i'll do just that and i'll get back to you!
@tpmabb you're welcome :) Don't hesitate to ask any doubt you may have about this answer.
@ dic19 Ever since I added e.printStackTrace i've been getting a driver error but my other test program is working fine...what could be possibly wrong here? I'll make time for the tutorial
@tpmabb did you see this post? stackoverflow.com/a/5983038/1795530 Make sure the URL you're trying to connect with is ok.
0

Looks like you are not handling exceptions, just an empty catch statement.

4 Comments

Thanx..but i'm a rookie ...any suggested code i can put in the catch block
Print the exception stacktrace, so you can read the error thrown in the try block. Something like: System.out.println(e); or ...println(e.getMessage()) My guess is that, during the db operation an exception is raised, you catch it (through catch block) but you don't do anything with it.
You should also put the database port on your connection string. Have a look at Mysql Java connectivity
Added port...not helping.
0
INSERT INTO carz VALUES('"+jTextField2.getText()+"',"+jTextField1.getText()+",'"+jComboBox1.getSelectedItem()+"',"+jTextField3.getText()+")");

In the above insert query you are not enclosing varchars with '

change it to like this

INSERT INTO carz VALUES('"+jTextField2.getText()+"','"+jTextField1.getText()+"','"+jComboBox1.getSelectedItem()+"','"+jTextField3.getText()+"')");

5 Comments

Thanx @JqueryLearner...but for those textfields without single quotes...they are actually ints
@tpmabb If they are int then you must convert them into int using Integer.parseInt(jTextField1.getText()).
I understand...tried but still not working...i'm not getting any conversion error or any other error. It's just that the table is not being updated!
@tpmabb I am sure you are having errors. If you do e.printStackTrace() in catch block then you will get all errors.
You're right...I am getting a no suitable driver error but I used the exact same driver (as posted above) in another working program
0

If you are sure you are entering numeric values for the ID and displacement, you should be ok without enclosing with varchars. But really, what you should do is just put a System.out.println(e.getSQLState()) or e.getMessage() or e.getErrorCode() in the catch statement and just see what the error is. That will go a long way in figuring out this issue.

Try modifying the getConnection part to:

Class.forName("com.mysql.jdbc.Driver"); // Setup the connection with the DB 
connect = DriverManager .getConnection("jdbc:mysql://localhost/feedback?" + "user=sqluser&password=sqluserpw");

And as AJ commented, put e.printStackTrace() in your catch block as well to get the most detailed info on what's going on in the JDBC process.

6 Comments

Cool...let me try that now.
Tried that...it's returning 08001
I think that is a "No suitable driver" error. Are you sure you included the mysql jar file for jdbc? I know you said you already tested the connection and it seemed to work. But googling sqlstate 08001 seems to point to that
I'm not sure if the Class.forName line is required either. Try the following two lines of code for setting up the connection. Class.forName("com.mysql.jdbc.Driver"); // Setup the connection with the DB connect = DriverManager .getConnection("jdbc:mysql://localhost/feedback?" + "user=sqluser&password=sqluserpw");
You know, the weird thing is that i have another program that works fine on the same machine it's just this one (with the same code except it's a different database) which isn't working. So I don't think it's a problem with the jdbc driver.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.