【问题标题】:Exception during connection to JDBC MySQL连接到 JDBC MySQL 时出现异常
【发布时间】:2019-07-14 10:53:34
【问题描述】:

下午好:我是来自西班牙的化学老师。我不是一个经验丰富的程序员,但我决定创建一个小程序来帮助我的学生学习我的学科。我正在用 Java 创建这个小程序,我正在尝试连接数据库以通过原子序数接收其信息。其实,我也想通过其他参数来做,但我不知道怎么做。问题是它反弹了异常或者它没有正确连接到数据库。我附上了我的数据库的完整代码和屏幕截图(顺便说一下,当我尝试将数据上传到数据库时它可以工作。):

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());
    }
}
}

这是我的数据库:

database phpmyadmin

这是在 NAt 中插入 1 时的例外情况:

Actual Exception

【问题讨论】:

  • 您能提供异常堆栈跟踪吗?
  • 您应该打印异常的堆栈跟踪并编辑您的帖子以包含它。

标签: java mysql database exception jdbc


【解决方案1】:

查看您的 select 查询周围的代码,您正在运行

            nat.setText("");

然后

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

您希望nat.getText() 回到这里做什么?

当然,它会返回"",因为这是您将nat 的文本设置为的内容。然后,您要求您的数据库运行以下无效查询:

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

对 MySQL 数据库运行此操作将在您的屏幕截图中生成错误。

我猜解决方法是删除nat.setText(""); 行。

但是,不要使用字符串连接来构建 SQL 字符串,而是使用PreparedStatements。

换行

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

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

还有线条

              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()+")");

              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();

您还需要围绕对Integer.parseInt(...) 的调用添加一些错误处理:如果nat.getText()mat.getText() 不是有效整数,这些将抛出NumberFormatException

【讨论】:

    【解决方案2】:

    如果您可以附上或准确描述 sqlException 是什么可能会有所帮助,但据我所知,您的数据库连接 url 格式不正确。所以它可能没有连接到数据库

    您的网址是: Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/chem","root" ,"");

    通常您需要添加数据库正在运行的端口号,以便更改:

    "jdbc:mysql://localhost/chem"
    

    到:

    jdbc:mysql://localhost:3306/chem
    

    或者你的数据库运行的任何端口,从谷歌看起来默认端口号是 3360,但这取决于你如何设置你的数据库。但我认为这应该可以解决你的问题

    【讨论】:

    • 不可能,因为我上传数据到数据库的时候连接很好。无论如何,帖子将在几秒钟内被编辑。
    【解决方案3】:

    请尝试使用您的数据库客户端手动执行您的 sql 查询。 为此,您可以添加这样的代码或使用调试来获取 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);
    

    您需要获取实际的 SQL 字符串并手动测试它是否有效。

    【讨论】:

    • 不是这样的。我得到了同样的例外。
    • 你能提供整个堆栈跟踪吗?
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    相关资源
    最近更新 更多