skip to Main Content

Good Afternoon: I’m a chemistry teacher from Spain. I am not an experimented programmer, but I decided to create a small program to help my students with my subject. I am creating this small program in Java where I’m trying to connect with a database in order to receive its information through the Atomic Number. Actually, I also want to do it through the other parameters, but I’m not shure about how to do it. The thing is that it bounces the exception or it doesn’t connect properly to the database. I attatch the full code and a screenshot of my database (By the way, when I try to upload data to the database it works.):

package chemInterface;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;



import java.awt.Color;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;

public class Oxidaciones extends JFrame {

private JPanel contentPane;
private JPasswordField pass;
private JTextField smb;
private JTextField elm;
private JTextField ox;
private JTextField nat;
private JTextField mat;

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

/**
 * Create the frame.
 */
public Oxidaciones() {
    setFont(new Font("Courier Prime", Font.PLAIN, 12));
    setTitle("Interface");
    setForeground(Color.BLUE);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setForeground(Color.BLUE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblSmbolo = new JLabel("Smb");
    lblSmbolo.setFont(new Font("Courier Prime", Font.PLAIN, 11));
    lblSmbolo.setBounds(10, 30, 67, 14);
    contentPane.add(lblSmbolo);

    JLabel lblElemento = new JLabel("Elm");
    lblElemento.setFont(new Font("Courier Prime", Font.PLAIN, 11));
    lblElemento.setBounds(10, 52, 67, 14);
    contentPane.add(lblElemento);

    JLabel lblOxidacin = new JLabel("Ox");
    lblOxidacin.setFont(new Font("Courier Prime", Font.PLAIN, 11));
    lblOxidacin.setBounds(10, 77, 67, 14);
    contentPane.add(lblOxidacin);

    JLabel lblNAtmico = new JLabel("NAt");
    lblNAtmico.setFont(new Font("Courier Prime", Font.PLAIN, 11));
    lblNAtmico.setBounds(10, 102, 86, 14);
    contentPane.add(lblNAtmico);

    JLabel lblMAtmica = new JLabel("MAt");
    lblMAtmica.setFont(new Font("Courier Prime", Font.PLAIN, 11));
    lblMAtmica.setBounds(10, 127, 86, 14);
    contentPane.add(lblMAtmica);

    pass = new JPasswordField();
    pass.setBounds(90, 166, 67, 20);
    contentPane.add(pass);

    JLabel lblPass = new JLabel("Pass");
    lblPass.setFont(new Font("Courier Prime", Font.PLAIN, 11));
    lblPass.setBounds(10, 169, 67, 14);
    contentPane.add(lblPass);

    smb = new JTextField();
    smb.setBounds(67, 25, 86, 20);
    contentPane.add(smb);
    smb.setColumns(10);

    elm = new JTextField();
    elm.setColumns(10);
    elm.setBounds(67, 47, 86, 20);
    contentPane.add(elm);

    ox = new JTextField();
    ox.setColumns(10);
    ox.setBounds(67, 72, 86, 20);
    contentPane.add(ox);

    nat = new JTextField();
    nat.setColumns(10);
    nat.setBounds(67, 97, 86, 20);
    contentPane.add(nat);

    mat = new JTextField();
    mat.setColumns(10);
    mat.setBounds(67, 127, 86, 20);
    contentPane.add(mat);

    JLabel lblResultado = new JLabel("");
    lblResultado.setBounds(243, 232, 46, 14);
    contentPane.add(lblResultado);


    JButton compile = new JButton("Compile");
    compile.addActionListener(new ActionListener() {
        @SuppressWarnings("deprecation")
        public void actionPerformed(ActionEvent arg0) {


            //COMPILE Presionado



                //INSERT BETWEEN HERE

                ox.setText("");
                elm.setText("");
                mat.setText("");
                nat.setText("");
                smb.setText("");

                try {
                Connection conexion=DriverManager.getConnection("jdbc:mysql://localhost/chem","root" ,"");
                Statement comando=conexion.createStatement();
                ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
                if(registro.next()==true) {
                    smb.setText(registro.getString("simbolo"));
                    ox.setText(registro.getString("oxidacion"));
                    elm.setText(registro.getString("elemento"));
                    mat.setText(registro.getString("matom"));
                } else {lblResultado.setText("No existe");}
                conexion.close();
                } catch(SQLException ex) {setTitle(ex.toString());}





            //AND HERE  

            }






    });
    compile.setBounds(7, 194, 89, 23);
    contentPane.add(compile);

    JButton clear = new JButton("Clear");
    clear.setBounds(7, 228, 89, 23);
    contentPane.add(clear);

    JButton alta = new JButton("Alta");
    alta.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {


            //BOTON ALTA PRESIONADO

            lblResultado.setText("");

            try {
                  Connection conexion=DriverManager.getConnection("jdbc:mysql://localhost/chem","root", "");
                  Statement comando=conexion.createStatement();
                  comando.executeUpdate("insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")");
                  conexion.close();
                  lblResultado.setText("se registraron los datos");
                  elm.setText("");
                  ox.setText("");
                  nat.setText("");
                  mat.setText("");
                  smb.setText("");
                } catch(SQLException ex){
                  setTitle(ex.toString());
                }

        }
    });
    alta.setBounds(335, 228, 89, 23);
    contentPane.add(alta);


    cargarDriver();
}

private void cargarDriver() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    }
    catch(Exception ex) {
        setTitle(ex.toString());
    }
}
}

Here is my database:

database phpmyadmin

And here is the exception when inserting 1 into NAt:

Actual Exception

3

Answers


  1. If you could attach or describe exactly what the sqlException is that might help, but from what I can see your database connection url is malformed. So its probably not connecting to the database

    your url is:
    Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/chem","root" ,"");

    Normally you need to add a port number that the database is running on so changing the:

    "jdbc:mysql://localhost/chem"
    

    to:

    jdbc:mysql://localhost:3306/chem
    

    or whatever the port your database is running on, from a google it looks like the default port number is 3360 but it depends on how you have setup your database. But i think that should solve your problem

    Login or Signup to reply.
  2. Please try to execute your sql query manually with your DB client.
    To do this you can add code like this or use debugging to get the sql string value and test it:

    String sqlString = "insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")";
    System.out.println(sqlString);
    comando.executeUpdate(sqlString);
    

    You need to get the actual SQL string and test it manually if it works.

    Login or Signup to reply.
  3. Taking a look at your code around your select query, you are running

                nat.setText("");
    

    and then

                ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
    

    What do you expect nat.getText() to return here?

    Of course, it will return "" because that’s what you’ve set the text of nat to. You’re then asking your database to run the following invalid query:

        select elemento,simbolo,oxidacion,matom from form where natom=
    

    Running this against a MySQL database will generate the error in your screenshot.

    I’m guessing that the fix is to delete the line nat.setText("");.

    However, instead of building up SQL strings using string concatenation, please use PreparedStatements instead.

    Replace the lines

                Statement comando=conexion.createStatement();
                ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
    

    with

                PreparedStatement comando=conexion.prepareStatement(
                    "select elemento,simbolo,oxidacion,matom from form where natom=?");
                comando.setInt(1, Integer.parseInt(nat.getText()));
                ResultSet registro = comando.executeQuery();
    

    and the lines

                  Statement comando=conexion.createStatement();
                  comando.executeUpdate("insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")");
    

    with

                  Statement comando=conexion.prepareStatement(
                      "insert into form(elemento,simbolo,oxidacion,natom,matom) values (?,?,?,?,?)");
                  comando.setString(1, elm.getText());
                  comando.setString(2, smb.getText());
                  comando.setString(3, ox.getText());
                  comando.setString(4, Integer.parseInt(nat.getText()));
                  comando.setString(5, Integer.parseInt(mat.getText()));
                  comando.executeUpdate();
    

    You will also need to add some error-handling around the calls to Integer.parseInt(...): these will throw NumberFormatException if either nat.getText() or mat.getText() isn’t a valid integer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search