Java swing jtable sql

MySQL Record display in JTable

We will connect to MySQL database and read details here on how to connect to MySQL and execute query. We will collect 4 rows only by using LIMIT query.

SELECT * FROM STUDENT LIMIT 0,4

Using this query we will get a record set of having first 4 rows of data from our student table.
We will loop through this record set to store each row data in our 2-D array data.

 int i=0; while(rs.next()) < for(int j=0;j<5;j++) < //System.out.print(rs.getString(j+1)); data[i][j]=rs.getString(j+1); >//System.out.println(); i=i+1; >

In our JTable.java file we have already added one JTable. Learn more on how to add JTable here.

Now we will create one object of class my_mysql.java to access the object my_db_select() to get the data.

String[] column= ; my_mysql obj=new my_mysql(); // Object is created //Collect the data using the object obj.my_db_select() with column jt1 = new javax.swing.JTable(obj.my_db_select(),column);

Displaying records in JTable

We have given the data input by using obj.my_db_select(). This runs the my_db_select() method of my_mysql.java class to get the 2-D array of 4 records.

JTable.java

import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JScrollPane; public class JTable extends JFrame < private JPanel contentPane; private javax.swing.JTable jt1; /** * Launch the application. */ public static void main(String[] args) < EventQueue.invokeLater(new Runnable() < public void run() < try < JTable frame = new JTable(); frame.setVisible(true); >catch (Exception e) < e.printStackTrace(); >> >); > /** * Create the frame. */ public JTable() < setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 400, 305); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 64, 366, 107); contentPane.add(scrollPane); //My_test obj=new My_test();// with test data my_mysql obj=new my_mysql(); String[] column= ; //jt1=new javax.swing.JTable(obj.my_test_select(),column);//test data jt1 = new javax.swing.JTable(obj.my_db_select(),column); scrollPane.setViewportView(jt1); > >

my_mysql.java

import java.sql.*; public class my_mysql < public String[][] my_db_select() < //////////// String[][] data = new String[4][5]; // [rows][columns] try< Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/my_tutorial","root","test"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT * FROM STUDENT LIMIT 0,4"); // Looping to store result in returning array data // int i=0; while(rs.next()) < for(int j=0;j<5;j++) < //System.out.print(rs.getString(j+1)); data[i][j]=rs.getString(j+1); >//System.out.println(); i=i+1; > // Below lines to check data before returning. // /* for (int x=0;x System.out.println(); > */ con.close(); >catch(Exception e) < System.out.println(e);>////////////////////////////// return data; > >

download

Download the Java Files here ( right click and save link as to download files ) .

Читайте также:  Robot framework with python

Источник

How to Retrieve Data From Database and Display it in JTable Using Java Swing

Hello Friends, Welcome to my new tutorial and in this tutorial, we will learn how to retrieve data from database and display it in JTable using Java Swing with simple and easy steps. A Java JTable is a class that is used to display data in the form of rows and columns.

In my previous tutorial, we learned how to install MySQL Workbench on Windows, Mac, and Ubuntu Operating System, and Now we will learn how to fetch data from the database and populate it in JTable.

I have used Eclipse IDE in this tutorial for the program development, but You can use any IDE like NetBeans or Intellij IDEA because the programming logic will be the same.

For the database, I have used MySQL Workbench , which is nothing but a GUI version of the MySQL console , where we can visually design, model, and generates databases.

I have also given the program’s source code at the end of this tutorial from where you can download it.

So let’s start our tutorial on how to retrieve data from database and display it in JTable using Java Swing.

How to Retrieve Data From Database and Display it in JTable Using Java Swing

First of all, I want to summarize what I am going to do in this tutorial. I am going to create a database in the back-end with a table in it named student and In the front end, I will set up the GUI, and when I will input the name of the student and click on the “Fetch Data” button, the table should show up with the details of that particular student.

Creating Database in MySQL Workbench

  • open MySQL WorkBench and then go to Database>Connect to Database.

How to retrieve data from from database and display it in jtable using java swing - fig 1

  • A pop-up window will be opened just click on ok.

  • Once you click on “ok” it will ask you for a password. It is the same password which you have used during the installation process. So enter the correct password and then click on the “ok” button.

  • Now create a database (studentDatabse in this example), and inside that database, create a table ( student in this example) with the following fields.
    • USERNAME
    • ROLLNO
    • DEPARTMENT

  • Now insert some values into it.

Setting Up the GUI

  • The next thing you have to do is set up the GUI to add the components to it.
  • Go to Eclipse IDE and create a new Java Project.
  • For this, you click on the Java Project under the new section of File Menu (File>>New>>Java Project).

How to retrieve data from from database and display it in jtable using java swing

  • Now give a name to your project (FetchDataExample in this example) and click on “Finish”.

How to retrieve data from from database and display it in jtable using java swing

  • Now right click on the project and create a new Java class (New>>Class).

How to retrieve data from from database and display it in jtable using java swing

  • Now give a name to your class( FetchData in this Example), tick mark on the public static void main(String[] args), and then click on the Finish button as shown in the figure below.

How to retrieve data from from database and display it in jtable using java swing

  • Now Implement the ActionListener interface to our class so that we will be able to do some button click event in our program. And if we are implementing the ActionListener interface in our class, we have to override it’s method actionPerformed() into our class.
  • Now create the window using the JFrame class of swing, and it’s methods then add components to it.
  • The components are,
    • one JLabel (username label)
    • one JTextField ( For entering the username)
    • Two JButtons ( one for fetching data and one for resetting the username text field)

    GridBagConstraints bagConstraints = new GridBagConstraints ( ) ; //creating object of GridBagConstratints

    bagConstraints . insets = new Insets ( 15 , 40 , 0 , 0 ) ; //Setting the padding between the components and neighboring components

    How to retrieve data from from database and display it in jtable using java swing

    • Now run your program
    • As you can see, the window is successfully created, and components are added to it.

    Connecting to Database

    • In order to connect your Java program with MySQL database, you need to include MySQL JDBC driver which is a JAR file, namely mysql-connector-java-5.1.49-bin.jar. The version number in the Jar file can be different.
    • You can download the latest version of MySQL connector from this link (MySQL Connector Java download) As shown in the figure below.

    • Extract the zip archive and you will get the jar file.
    • Next, you have to include this jar file into your program so that you will be able to connect your java program with MySQL database.
    • Right-click on the project, go to the properties section then select Java Build Path and click on the Add External JARs button.

    • After clicking on the button a pop-up window will appear where you have to select and open the jar file.

    • You can see the added Jar file as shown in the figure below. Now click on the Apply and Close button.

    • Now we want that when we enter the username and click on the Fetch data Button, that particular student’s details should show up in a new window inside the JTable. And if we Enter the wrong username and click on the Fetch data button, then the message dialog box should show a specific message.
    • If we click on the Reset Button, then it should clear the username text field.

    Setting up JTable and Retrieving Data From the Database to JTable

    • For this, you need to create objects of,
      • A JFrame
      • A JTable
      • A DefaultTableModel (this is used when no model is specifically defined)
      • A Connection object
      • A Statement object

      Источник

      Java JDBC How to — Display Records From MySQL Database using JTable

      We would like to know how to display Records From MySQL Database using JTable.

      Answer

      import java.awt.BorderLayout; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.Vector; /*from w w w. j a v a2 s. c om*/ import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; public class Main extends JFrame < public Main() throws Exception < ArrayList columnNames = new ArrayList(); ArrayList data = new ArrayList(); String url = "jdbc:mysql://localhost:3306/yourdb"; String userid = "root"; String password = "sesame"; String sql = "SELECT * FROM animals"; Connection connection = DriverManager.getConnection(url, userid, password); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData md = rs.getMetaData(); int columns = md.getColumnCount(); for (int i = 1; i while (rs.next()) < ArrayList row = new ArrayList(columns); for (int i = 1; i data.add(row); > Vector columnNamesVector = new Vector(); Vector dataVector = new Vector(); for (int i = 0; i < data.size(); i++) < ArrayList subArray = (ArrayList) data.get(i); Vector subVector = new Vector(); for (int j = 0; j < subArray.size(); j++) < subVector.add(subArray.get(j)); >dataVector.add(subVector); > for (int i = 0; i < columnNames.size(); i++) columnNamesVector.add(columnNames.get(i)); JTable table = new JTable(dataVector, columnNamesVector) < public Class getColumnClass(int column) < for (int row = 0; row < getRowCount(); row++) < Object o = getValueAt(row, column); if (o != null) < return o.getClass(); > > return Object.class; > >; JScrollPane scrollPane = new JScrollPane(table); getContentPane().add(scrollPane); JPanel buttonPanel = new JPanel(); getContentPane().add(buttonPanel, BorderLayout.SOUTH); > public static void main(String[] args) throws Exception < Main frame = new Main(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); > >

      java2s.com | © Demo Source and Support. All rights reserved.

      Источник

Оцените статью