我正在制作GUI。当用户单击JButton b1时可以插入数据。后端数据库有1个表,该表是电影并且有两列。第一列的名称是title,数据类型是varchar,第二列的名称是year,其数据类型是integer。但是我不知道该怎么写借助文本字段在程序中查询。我在查询中尝试了许多代码,但没有任何反应。
码:

public class A extends JFrame{

    private JTextField t1;
    private JTextField t2;
    private JLabel l1;
    private JLabel l2;
    private JButton b1;

    private  Connection conn;
    private Statement state;
    String server = "jdbc:mysql://localhost/demo";
    String user="root";
    String pass="65";

    public A(){
        super("Query");

        setLayout(null);

        t1= new JTextField();
        t1.setBounds(173, 152, 128, 27);
        add(t1);

        //for year
        t2= new JTextField();
        t2.setBounds(173, 105, 128, 27);
        add(t2);


        l1= new JLabel("title");
        l1.setBounds(99, 101, 42, 37);
        add(l1);

        l1= new JLabel("year");
        l1.setBounds(99, 148, 42, 37);
        add(l1);

        b1= new JButton("Insert");
        b1.setBounds(50, 222, 102, 37);
        add(b1);
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                try{

            CreateQuery("insert into movies (title,year) values('"+t1.getText()+"') ");



                }
                catch(Exception e1){
                    e1.printStackTrace();
                }
            }
        });

        setSize(450,450);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
    }



    public void CreateQuery(String w){
        try{

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

            conn=DriverManager.getConnection(server,user,pass);
             state =  conn.createStatement();
             state.executeUpdate(w);
             JOptionPane.showMessageDialog(null, "Query Executed");
        }

        catch(Exception e){
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

    }

}

主要:
public class Main {

    public static void main(String[] args) {
        A obj = new A();
}
}

最佳答案

您可以通过两种方式执行此操作,第一种是您正在使用的过程,即使用createStatement

您必须同时设置标题和年份。

CreateQuery("insert into movies (title,year) values('"+t1.getText()+"', " + t2.getText() + ")");

第二个是使用prepareStatement,
方法调用
CreateQuery(t1.getText(), t2.getText());

方法,
public void CreateQuery(String title, String year){
        try{

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

            conn=DriverManager.getConnection(server,user,pass);
             PreparedStatement state =  conn.prepareStatement("insert into movies (title,year) values('?', ?)");
             state.setString(1, title);
             state.setInt(1, new Integer(year));
             state.executeUpdate();
             JOptionPane.showMessageDialog(null, "Query Executed");
        }

        catch(Exception e){
            JOptionPane.showMessageDialog(null, e.getMessage());
        }

    }

10-05 21:11
查看更多