简体   繁体   English

使用 JDBC 插入 JButton

[英]Using JDBC to insert JButton

I would like to know is it possible to extract the data from the database file and directly put it in the JButton to let the user select?我想知道是否可以从数据库文件中提取数据并将其直接放在JButton中让用户选择?

For example,例如,

The first GUI will let the user click a JButton (Food).第一个 GUI 将让用户单击JButton (食物)。

Then the second GUI will prompt out all the names from the database.然后第二个 GUI 将提示出数据库中的所有名称。

Is it possible to do that?有可能这样做吗?

Can I have a sample code?我可以有一个示例代码吗? Just a simple one will do.一个简单的就可以了。

Hey in this case I explain how to display Employee information from a database in a Frame.嘿,在这种情况下,我解释了如何在框架中显示来自数据库的员工信息。 The NetBeans IDE is used for creating this application. NetBeans IDE 用于创建此应用程序。

How to Display Emp Information in a New Frame如何在新帧中显示 Emp 信息

For creating this app we need the following files.为了创建这个应用程序,我们需要以下文件。

Java file ojdbc.jar file NetBeans IDE SQL table Java 文件 ojdbc.jar 文件 NetBeans IDE SQL 表

1. Java File 1.Java文件

This Java contains the programming code.该 Java 包含编程代码。 In this file we use Swing components to display the emp data in a new frame after the employee name selection.在此文件中,我们使用 Swing 组件在员工姓名选择后的新框架中显示 emp 数据。

What we can do我们能做什么

A. Import several packages A.导入几个包

First we need to import the following packages:首先我们需要导入以下包:

javax.swing.*;
java.awt.*;
java.awt.event.*;
java.sql.*;
java.util.Vector;

The Swing package is used for the swing components. Swing 包用于摆动组件。 All swing components are defined within this package.所有摆动组件都在此包中定义。 The AWT package provides the event handling mechanism, in other words it deals with events like "button-click". AWT 包提供了事件处理机制,换句话说,它处理诸如“按钮单击”之类的事件。 The SQL package creates the JDBC connection. SQL 包创建 JDBC 连接。

B. Extend the JFrame components and implements the ActionListener B.扩展JFrame组件并实现ActionListener

Extends the JFrame components and implement the ActionListener as in the following:扩展JFrame组件并实现ActionListener ,如下所示:

class EmpSearchApp extends JFrame implements ActionListenerEmpSearchApp扩展JFrame实现ActionListener

C. Declare components C. 声明组件

Now declare the following components:现在声明以下组件:

JLabel l, l1, l2, l3, l4,l5;

JButton b;

JTextField tf1, tf2, tf3, tf4;

JComboBox bx;
String str;

D. Declare Frame components D. 声明 Frame 组件

Now declare Frame components in a default constructor as in the following:现在在默认构造函数中声明 Frame 组件,如下所示:

Syntax句法

EmpSearchApp()
{
......
......
try{
//JDBC CODE
}Catch(Exception ex)
{
System.out.println(ex)
}
......
}

Note: In the dotted part we declare and add various components of Swing;注意:虚线部分我们声明并添加了Swing的各个组件; in this part the JDBC code is also used to get an Emp name from the database table that can used in JComboBox.在这部分中, JDBC代码还用于从数据库表中获取可在 JComboBox 中使用的 Emp 名称。 The full code I'll show you below here;我将在下面向您展示完整的代码; I'll only summarize for you what I can do.我只会为你总结我能做的。

D. Add a ActionListener D. 添加一个 ActionListener

Add a ActionListener for the button clicked event as in the following:为按钮单击事件添加一个 ActionListener,如下所示:

public void actionPerformed(ActionEvent e) {

                   showData();
            }

Note: If we have multiple buttons then we can use " if (e.getSource() == buttonName) ".注意:如果我们有多个按钮,那么我们可以使用“ if (e.getSource() == buttonName) ”。 But in this app I can use only a single button " Submit " so there is no need to use "e.getSource".但在这个应用程序中,我只能使用一个按钮“ Submit ”,因此无需使用“e.getSource”。 I used a method " showData() ".我使用了一种方法“ showData() ”。 In that method I wrote new frame code.在那种方法中,我编写了新的框架代码。

E. Create a new Frame E. 创建一个新框架

Create a new Frame in the showData() method as in the following:
public void showData() {
.........
try{
//JDBC CODE
}Catch(Exception ex)
{
System.out.println(ex)
}
.........
}

F. Create a main method and run the constructor F. 创建一个 main 方法并运行构造函数

Finally, create a main method and run the constructor as in the following:最后,创建一个 main 方法并运行构造函数,如下所示:

public static void main(String arr[]) {

        new EmpSearchApp();
    }

2. ojdbc.jar file 2. ojdbc.jar 文件

This JAR file provides a way to set up a Java connection with an Oracle Database.此 JAR 文件提供了一种建立与 Oracle 数据库的 Java 连接的方法。 Since the JDBC connection is provided by the Oracle Server vendor we need to import this JAR file in our library folder.由于 JDBC 连接是由 Oracle Server 供应商提供的,我们需要在我们的库文件夹中导入这个 JAR 文件。

3. NetBeans IDE 3. NetBeans IDE

This IDE is used to create this application.此 IDE 用于创建此应用程序。 Since we have a choice we can simply create this app with any text editor, like Notepad, Notepad++, etcetera.由于我们可以选择,因此我们可以使用任何文本编辑器(例如 Notepad、Notepad++ 等)简单地创建此应用程序。 But by using NetBeans we can create the Frame and add components like "button", "label", etcetera directly without writing its code.但是通过使用 NetBeans,我们可以创建框架并直接添加诸如“按钮”、“标签”等组件,而无需编写其代码。 I explained the advantages of the IDE in my previous article "Advantages Of Netbeans IDE" through which you can see the difference.我在之前的文章“Netbeans IDE 的优势”中解释了 IDE 的优点,通过它你可以看到不同之处。

4. emp.sql table 4.emp.sql表

For fetching records we need a database table;为了获取记录,我们需要一个数据库表; for that we create an "emp" table in our "freeman" database.为此,我们在“freeman”数据库中创建了一个“emp”表。

Syntax句法

emp.sql emp.sql

create table emp
 (
    uname varchar2(20), umail varchar2(30),
    upass varchar2(20), ucountry varchar2(20)
 );

Insert some rows into it as in the following:在其中插入一些行,如下所示:

1. insert into emp values ('freeman', 'test@tt.com', 'welcome', 'Iran');

2. insert into emp values ('sam', 'sam@ss.com' , '555', 'USA');

Now let's start creating this app.现在让我们开始创建这个应用程序。 Use the following procedure to do that in the NetBeans IDE.使用以下过程在 NetBeans IDE 中执行此操作。

Step 1第1步

Open the NetBeans IDE.打开 NetBeans IDE。

Step 2第2步

Choose "Java" -> "Java application" as shown below.选择“Java”->“Java 应用程序”,如下所示。

在此处输入图片说明

Step 3第 3 步

Provide "EmpSearchApp" for your project name as in the following and click on "Finish".为您的项目名称提供“EmpSearchApp”,如下所示,然后单击“完成”。

在此处输入图片说明

Step 4第四步

Create a new Java Class "EmpSearchApp" with the following.使用以下内容创建一个新的 Java 类“EmpSearchApp”。

EmpSearchApp.java

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.sql.*;

import java.util.Vector;



public class EmpSearchApp extends JFrame implements ActionListener {



    JLabel l, l1, l2, l3, l4, l5;

    JButton b;

    JTextField tf1, tf2, tf3, tf4;

    JComboBox bx;

    String str;



    EmpSearchApp() {

        setVisible(true);

        setSize(700, 700);

        setLayout(null);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setTitle("JDBC DEMO");



        l = new JLabel("Select Name:");

        b = new JButton("Submit");



        tf1 = new JTextField();

        tf2 = new JTextField();

        tf3 = new JTextField();

        tf4 = new JTextField();



        l.setBounds(20, 20, 200, 20);

        b.setBounds(50, 50, 150, 30);



        add(l);

        add(b);



        tf1.setEditable(false);

        tf2.setEditable(false);

        tf3.setEditable(false);

        tf4.setEditable(false);

        b.addActionListener(this);



        try {

            Class.forName("oracle.jdbc.driver.OracleDriver");

            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@mcndesktop07:1521:xe", "freeman", "welcome");

            PreparedStatement ps = con.prepareStatement("select uname from emp");

            ResultSet rs = ps.executeQuery();

            Vector v = new Vector();

            while (rs.next()) {

                String s = rs.getString(1);



                v.add(s);

            }

            bx = new JComboBox(v);

            bx.setBounds(240, 20, 200, 20);

            add(bx);



        } catch (Exception ex) {

            System.out.println(ex);

        }



    }



    public void actionPerformed(ActionEvent e) {

        showData();

    }



    public void showData() {

        JFrame f1 = new JFrame();

        f1.setVisible(true);

        f1.setSize(500, 500);

        f1.setLayout(null);

        f1.setTitle("JDBC DEMO");



        l5 = new JLabel("Displaying Emp Data:");       

        l5.setForeground(Color.red);

        l5.setFont(new Font("Serif", Font.BOLD, 20));

        l1 = new JLabel("Emp Name:");

        l2 = new JLabel("Emp Email:");

        l3 = new JLabel("Emp pass:");

        l4 = new JLabel("Emp Country:");



        l5.setBounds(100, 50, 300, 30);

        l1.setBounds(20, 110, 200, 20);

        l2.setBounds(20, 140, 200, 20);

        l3.setBounds(20, 170, 200, 20);

        l4.setBounds(20, 200, 200, 20);



        tf1.setBounds(240, 110, 200, 20);

        tf2.setBounds(240, 140, 200, 20);

        tf3.setBounds(240, 170, 200, 20);

        tf4.setBounds(240, 200, 200, 20);



        f1.add(l5);

        f1.add(l1);

        f1.add(tf1);

        f1.add(l2);

        f1.add(tf2);

        f1.add(l3);

        f1.add(tf3);

        f1.add(l4);

        f1.add(tf4);



        str = (String) bx.getSelectedItem();

        try {

            Class.forName("oracle.jdbc.driver.OracleDriver");

            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@mcndesktop07:1521:xe", "freeman", "welcome");

            PreparedStatement ps = con.prepareStatement("select * from emp where uname=?");

            ps.setString(1, str);

            ResultSet rs = ps.executeQuery();

            while (rs.next()) {



                tf1.setText(rs.getString(1));

                tf2.setText(rs.getString(2));

                tf3.setText(rs.getString(3));

                tf4.setText(rs.getString(4));



            }

        } catch (Exception ex) {

            System.out.println(ex);

        }

    }



    public static void main(String arr[]) {

        new EmpSearchApp();

    }
}

Step 5第 5 步

Now your project is ready to run.现在您的项目已准备好运行。

Right-click on the project menu and choose "Run".右键单击项目菜单并选择“运行”。 The following output is generated.生成以下输出。

Good luck祝你好运

List<String> foodNames = new ArrayList<>();
ResultSet rs = this.connection.createStatement().executeQuery("SELECT Name FROM Food");
while (rs.next())
{
    foodNames.add(rs.getString(1));
}

Now you've got a list foodNames with all names from all the foods.现在您已经获得了一个包含所有食物名称的foodNames列表。

You could implement the code like this, where the method "btnFoodActionPerformed(ActionEvent)" is called when you press the button "Food".你可以实现这样的代码,当你按下按钮“Food”时调用方法“btnFoodActionPerformed(ActionEvent)”。

private void btnFoodActionPerformed(java.awt.event.ActionEvent evt)
{
    List<String> foodNames = new ArrayList<>();
    ResultSet rs = this.connection.createStatement().executeQuery("SELECT Name FROM Food");
    while (rs.next())
    {
        foodNames.add(rs.getString(1));
    }
//do some stuff with the list
}

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

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