如何在jButton中用java执行特定的SQL查询

如何在jButton中用java执行特定的SQL查询

问题描述:

是否有可能在单击jButton时直接执行SQL查询?如何在jButton中用java执行特定的SQL查询

例如,在jDialog中,我有一个用于用户名和保存按钮的文本框。

JButton的操作:

@Action 
public void saveNewUser() { 
    Statement s = con.createStatement(); 
    s.executeUpdate("INSERT INTO User (username) " + " VALUES ('"+ username + "')") 
} 

所以我需要从用户名文本框获取字符串,但如何?

+1

是的,任何事情都是可能的。阅读摇摆教程以掌握框架。 http://docs.oracle.com/javase/tutorial/uiswing/ –

您应该查看Swing API。该文本字段将是一个JTextField。下面是对Java JDK API链接:http://docs.oracle.com/javase/6/docs/api/这里是一个直接的JTextField:http://docs.oracle.com/javase/6/docs/api/javax/swing/JTextField.html

下面是一些非常简单的代码,你想要做什么(我忽略布局,国际化功能,以及其他各种改进):

JTextField usernameTextField = new JTextField("Username:"); 
JButton saveButton = new JButton("Save"); 

saveButton.addActionListener(new ActionListener()) 
{ 
    public void actionPerformed(ActionEvent e) 
    { 
    String username = usernameTextField.getText(); 
    //Put validation code here if you want 

    //Then put your SQL insert statement code here 
    } 
}); 

//Generally you will be adding them to a JPanel, but can be a JFrame for simple cases 
panel.add(usernameTextField); 
panel.add(saveButton); 

... 
+0

谢谢你的回答 – user1036529

+0

如果你喜欢它,那么请接受它作为答案。 –