Join Two String Value using MySQL CONCAT Function in Java

0
44

This tutorial is all about “Join Two String Value using MySQL CONCAT Function in Java”. This will teach you on how you can join two string values from MySQL database and display it into a Table in Java. We use “CONCAT” function in MySQL Query to join to value.

MySQL CONCAT function is used to concatenate two strings to form a single string. In actual database, the first name and last name is set in specific column in MySQL. Using CONCAT, the first name and last name joined using CONCAT to form a single line of string when display in Table.

Join Two String Value using MySQL CONCAT Function in Java Steps

Create or add a new Form inside your source package and input your desired name.

Design your form just look like the image below.

Insert the following codes below to access the required libraries for this program.

  1. import java.sql.Connection;
  2. import java.sql.PreparedStatement;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import javax.swing.JOptionPane;
  6. import javax.swing.table.TableColumnModel;
  7. import net.proteanit.sql.DbUtils;

Insert the following codes below for variable declaration needed in accessing MySQL Database.

  1. Connection conn=null;
  2. ResultSet rs = null;

Insert the codes below inside your public method to connect to your MySQL Connection class. Check your MySQL Connection statement to identify your connection method. In my case, I used “MyDbConnection”.

  1. conn = dbConnection.MyDbConnection();

Create a new method inside your class. In my case, I use “loadData” method name.

  1. public final void loadData(){
  2.  
  3. }

Insert the following codes below inside your new created method. As you notice that CONCAT is in the SELECT query conbining the FirstName and LastName attribute from userinfo entity.

  1. try{
  2. String sql="SELECT concat(FirstName,' ',LastName) as NAME FROM userinfo";
  3. pst=conn.prepareStatement(sql);
  4. rs = pst.executeQuery(sql);
  5. jTable1.setModel(DbUtils.resultSetToTableModel(rs));
  6.  
  7. }catch(SQLException e) {
  8. JOptionPane.showMessageDialog(this, e.getMessage());
  9. }

Run your program and the output should look like the image below.

There are many ways to join two or more string values to form a single string in Java. This tutorial use CONCAT function in MySQL query to perform that feature. You can also use “+” sign to join two string variable in Java if you are working a program without database. If you have comments and suggestions regarding this tutorial, feel free to contact us.

Related Articles You May Like:

Facebook Comments
(Visited 47 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here