Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java sql查询_Java_Sql_Swing - Fatal编程技术网

java sql查询

java sql查询,java,sql,swing,Java,Sql,Swing,我有一个问题。我有一个数据库,我正在尝试编写代码,以便可以从java软件创建数据库中的记录 我有一个连接到数据库的连接器类,然后是一个registerStudent类,它允许用户在两个文本字段中键入值。然后,应使用这些值在数据库表中创建记录 当我点击submit按钮时,它给出以下错误代码: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at RegisterStudent$2.actionPerform

我有一个问题。我有一个数据库,我正在尝试编写代码,以便可以从java软件创建数据库中的记录

我有一个连接到数据库的连接器类,然后是一个registerStudent类,它允许用户在两个文本字段中键入值。然后,应使用这些值在数据库表中创建记录

当我点击submit按钮时,它给出以下错误代码:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at RegisterStudent$2.actionPerformed(RegisterStudent.java:99)
仅供参考-第99行代码=

con.stmt.executeUpdate("INSERT INTO staff (Name, Profession)"+"VALUES"+"("+"'"+name+"',"+"'"+profession+"')");
这是我为registerStudent类编写的代码:

import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.SQLException;


public class RegisterStudent
{

    public RegisterStudent() {
        initialize();
    }

    public JFrame frmRegisterStudent;

    Connector con;
    private JTextField textField_1;
    private JTextField textField_2;

    // initialise the frame
    private void initialize() {
        frmRegisterStudent = new JFrame();
        frmRegisterStudent.setTitle("LEC AdminPro: RegisterStudents");
        frmRegisterStudent.setBounds(100, 100, 413, 225);
        frmRegisterStudent.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frmRegisterStudent.setLocationRelativeTo(null);


        Border border = LineBorder.createGrayLineBorder();
        frmRegisterStudent.getContentPane().setLayout(null);
        con = new Connector();

        JPanel panel_1 = new JPanel();
        panel_1.setBounds(0, 0, 397, 189);
        frmRegisterStudent.getContentPane().add(panel_1);
        panel_1.setBorder(border);
        panel_1.setLayout(null);

        JLabel lblRegister = new JLabel("Register Student");
        lblRegister.setFont(new Font("Tahoma", Font.BOLD, 12));
        lblRegister.setBounds(10, 11, 124, 20);
        panel_1.add(lblRegister);

        JLabel lblSurname = new JLabel("Name");
        lblSurname.setFont(new Font("Arial", Font.PLAIN, 11));
        lblSurname.setBounds(10, 63, 69, 14);
        panel_1.add(lblSurname);

        JLabel lblDob = new JLabel("Profession");
        lblDob.setFont(new Font("Arial", Font.PLAIN, 11));
        lblDob.setBounds(10, 88, 69, 14);
        panel_1.add(lblDob);

        textField_1 = new JTextField();
        textField_1.setColumns(10);
        textField_1.setBounds(104, 63, 266, 20);
        panel_1.add(textField_1);

        textField_2 = new JTextField();
        textField_2.setColumns(10);
        textField_2.setBounds(104, 88, 266, 20);
        panel_1.add(textField_2);


        JButton btnNewButton = new JButton("Cancel");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                Object[] options = {"Yes", "No"};
                Component form = null;
                int n = JOptionPane.showOptionDialog(form, "Would you like to cancel the new Registration?", "Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,  null, options, options);
                if(n == JOptionPane.YES_OPTION) {
                frmRegisterStudent.setVisible(false);
            }

        }
        });
        btnNewButton.setBounds(280, 119, 89, 23);
        panel_1.add(btnNewButton);

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


            String name = textField_1.getText();    
            String profession = textField_1.getText();


                try {
            con.stmt.executeUpdate("INSERT INTO staff (Name, Profession)"+"VALUES"+"("+"'"+name+"',"+"'"+profession+"')");
            JOptionPane.showMessageDialog(frmRegisterStudent, "New Record has been added");

            } catch (SQLException e) {
            System.out.println("Record couldn't be added!");
            e.printStackTrace();
            }
            }
            });



        button.setBounds(181, 119, 89, 23);
        panel_1.add(button);


    }




    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                    try {
                RegisterStudent window = new RegisterStudent();
                window.frmRegisterStudent.setVisible(true);
                } catch (Exception e) {
                e.printStackTrace();
                }
            }
        });

        public void setVisible(boolean b) {
        frmRegisterStudent.setVisible(true);

}    
}

问题似乎出在
连接器
类中,该类有一个未初始化的
stmt
字段

使用该行,而不是带有NullPointerException的行

con.stmt = con.conn.prepareStatement("insert into staff (name, profession) values (?, ?)");
con.stmt.setString(1, name);
con.stmt.setString(2, profession);
con.stmt.executeUpdate();

但请注意,这是一种非常糟糕的设计。

您的连接器是否为空?我看到stmt是连接器中的一个字段,您初始化了它吗? 顺便说一下,在您的情况下,使用预处理语句要好得多,因为它将转义字符串(例如,如果字符串中有“.”)


可能是因为
con.stmt
为空。在
连接器
类中有什么?连接器构造是否以某种方式初始化了
stmt
字段?stmt=queryConnection.createStatement();是的,是这样的:这是代码连接连接;编制报表;结果集rs;publicstaticvoidmain(String[]args){connectionconn=null;尝试{stringusername=“root”;stringpassword=“”;stringurl=“jdbc:mysql://localhost/test“Class.forName(“com.mysql.jdbc.Driver”).newInstance();conn=DriverManager.getConnection(url、用户名、密码);System.out.println(“已建立数据库连接”);}还有一个catch和exception语句,但是它不适合这个注释。如果你喜欢,我可以单独编写。是的,它在连接器中为null。我如何初始化它,在哪个类中初始化它?你说使用一个prepared语句是什么意思,你能给我一个带有prepared语句的代码示例吗?非常感谢这是prepared statement sample.thank you amir.您能否再次重申我需要如何初始化连接器?您能否解释一下,我需要如何初始化?在我的连接器类中,我使用PreparedStatement stmt初始化;您应该创建一个连接类,例如通过DriverManager.createConnection(JDBC_URL、用户名、密码)在我的连接器类中,我得到了PreparedStatement stmt;@Pita:那么您已经声明了字段,但没有初始化它。将更改答案以反映这一点。
PreparedStatement pstmt = connection.prepareStatement("insert into staff (name, profession) values (?, ?)");
pstmt.setString(1, name);
pstmt.setString(2, profession);
pstmt.executeUpdate();