简体   繁体   English

如何使用java in swing在jButton上执行特定的SQL-Query

[英]How to execute a specific SQL-Query on a jButton with java in swing

Is it possible to execute a SQL query directly when clicking on a jButton? 单击jButton时是否可以直接执行SQL查询?

For example, in a jDialog I have a textfield for the Username and a savebutton. 例如,在jDialog中,我有一个用户名的文本字段和一个保存按钮。

jButton Action: jButton行动:

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

So I would need to get the String from the Username textfield, but how? 所以我需要从Username文本字段中获取String,但是如何?

You should review the Swing API. 您应该查看Swing API。 The textfield would be a JTextField. 文本字段是JTextField。 Here is a link to the Java JDK API: http://docs.oracle.com/javase/6/docs/api/ and Here is one directly to JTextField: http://docs.oracle.com/javase/6/docs/api/javax/swing/JTextField.html 以下是Java JDK API的链接: http//docs.oracle.com/javase/6/docs/api/ ,以下是JTextField的直接链接: http//docs.oracle.com/javase/6/文档/ API /使用javax /秋千/ JTextField.html

Here is some very simplified code that does what you want (I am ignoring layout, i18n, and other various improvements): 这是一些非常简化的代码,可以满足您的需求(我忽略了布局,i18n和其他各种改进):

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

...

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

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