Search code examples
javamysqlsqlexception

Java Swing, Mysql error from PreparedStatement


This is my table on mysql: enter image description here

This is my Java code:

                public static final String  username  = "root";
public static final String  password  = "sundayman";
public static final String  connect  = "jdbc:mysql://localhost:3306/lives";
Connection sqlConn = null;
PreparedStatement pst = null;
ResultSet rs = null;
                try {

                Class.forName("com.mysql.jdbc.Driver");

                sqlConn = DriverManager.getConnection(connect, username, password);

                pst = (PreparedStatement)sqlConn.prepareStatement("insert into lives_table(Name,Latin Name,Live's Class,Cell Structure,Nutrition,Respiratory,Move,Reproductive)"+"values(?,?,?,?,?,?,?,?)");

                pst.setString(1, l.getName());
                pst.setString(2, l.getLatin());
                pst.setString(3, l.getLive_class());
                pst.setString(4, l.getCell_type());
                pst.setString(5, l.getFeed());
                pst.setString(6, l.getO2());
                pst.setString(7, l.getMove());
                pst.setString(8, l.getReproductive());
               
                pst.executeUpdate();
                JOptionPane.showMessageDialog(null, "Live Recorded!");
                

                

            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex);
            }
    }

I got this Error: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

What's wrong?


Solution

  • If you need column names to have special characters, you must delimit them in back-ticks:

    WRONG:

    insert into lives_table(Name,Latin Name,Live's Class,Cell Structure,Nutrition,Respiratory,Move,Reproductive)...
    

    RIGHT:

    insert into lives_table(Name,`Latin Name`,`Live's Class`,`Cell Structure`,Nutrition,Respiratory,Move,Reproductive)...
    

    Most people decide it is simpler to avoid using whitespace and punctuation characters in their column names.