简体   繁体   English

连接到JDBC MySQL期间发生异常

[英]Exception during connection to JDBC MySQL

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. 我正在用Java创建这个小程序,我试图与数据库连接以便通过原子序号接收其信息。 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 数据库phpmyadmin

And here is the exception when inserting 1 into NAt: 这是将1插入NAt时的例外情况:

Actual Exception 实际例外

Taking a look at your code around your select query, you are running 看看您select查询周围的代码,您正在运行

            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? 您期望nat.getText()返回什么?

Of course, it will return "" because that's what you've set the text of nat to. 当然,它将返回""因为这就是您将nat文本设置为的内容。 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. 针对MySQL数据库运行此操作将在您的屏幕截图中生成错误。

I'm guessing that the fix is to delete the line nat.setText(""); 我猜想解决办法是删除行nat.setText(""); .

However, instead of building up SQL strings using string concatenation, please use PreparedStatement s instead. 但是,不要使用字符串连接构建SQL字符串,而应使用PreparedStatement

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. 您还需要在对Integer.parseInt(...)的调用周围添加一些错误处理:如果nat.getText()mat.getText()不是有效的整数,则这些调用将引发NumberFormatException

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. 如果您可以附加或准确描述sqlException是什么,可能会有所帮助,但是从我的角度来看,您的数据库连接URL格式错误。 So its probably not connecting to the database 所以它可能没有连接到数据库

your url is: Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/chem","root" ,""); 您的网址是: 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. 或数据库正在运行的任何端口,从Google看来默认端口号是3360,但这取决于您如何设置数据库。 But i think that should solve your problem 但是我认为应该可以解决您的问题

Please try to execute your sql query manually with your DB client. 请尝试使用数据库客户端手动执行SQL查询。 To do this you can add code like this or use debugging to get the sql string value and test it: 为此,您可以添加如下代码或使用调试来获取sql字符串值并对其进行测试:

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. 您需要获取实际的SQL字符串并对其进行手动测试(如果可行)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM