How to concatenate 3 resultset values together in jtextfield? - java

I am trying to concatenate 3 resultset values from my database and display them together in one textfield but its not working i am getting only last value that is "city" displayed in textbox.
PreparedStatement stmt2 = con.prepareStatement("select bk_name as bank,bk_branch as branch,bk_add as city from bk_det WHERE rm_id = ?");
ResultSet rs2;
String rm2 = tf_rmid.getText().trim();
stmt2.setInt(1, Integer.parseInt(rm2));
rs2 = stmt2.executeQuery();
while (rs2.next()) {
tf_remby.setText(rs2.getString("bank"));
tf_remby.setText(rs2.getString("branch"));
tf_remby.setText(rs2.getString("city"));
}
I tried doing:
tf_remby.setText(rs2.getString("bank"+","+"branch"+","+"city"));
and also
tf_remby.setText(rs2.getString("bank"+"branch"+"city"));
but neither works. Does anyone have any suggestions/solutions?

In your while loop, you could try something like:
String text = rs2.getString("bank") + ", " +
rs2.getString("branch") + ", " +
rs2.getString("city");
tf_remby.setText(text);
But if you have multiple values in the result set, you'll only see the last bank/branch/city record anyway.

Related

While ResultSet is not executing?

I am trying to call two sets of data from two different tables to display in a JTextArea (jtaDisplay). The first table (emp_db) will get the employee number, name and surname. The second table (sec_clearance) will get the employee security clearance level.
The method is placed in the constructor so it will execute when the frame starts up, but whenever I run the frame it does not display the data. No error messages come up and the stack trace doesn't display any error messages.
I placed a JOptionPane in various places inside the method to see where the problem lies exactly and found that the while(rs.next()) statement is not executing as the JOptionPane displays outside the while statement but not inside it.
Here is the code I currently have:
try
{
String user = txtEmpTitle.getText();
String encuser = encrypt(user); //encrypting employee number with AES to read in database
String getEmpNum = "Select * from emp_db where emp_num = '" + encuser + "'";
String getSecLevel = "select secLevel from sec_clearance where emp_num = '" + encuser + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_database","root","pass123");
Statement stmt=conn.createStatement();
Statement stmt2=conn.createStatement();
ResultSet rs = stmt.executeQuery(getEmpNum);
ResultSet rs2 = stmt2.executeQuery(getSecLevel);
while(rs.next() && rs2.next())
{
String empNum = rs.getString("emp_num");
String empName = rs.getString("fname");
String empSname = rs.getString("sname");
String empSecLevel = rs2.getString("secLevel");
//decrypting data in database
String decNum = EmpEditDB.decrypt(empNum);
String decName = EmpEditDB.decrypt(empName);
String decSname = EmpEditDB.decrypt(empSname);
String decSecLevel = EmpEditDB.decrypt(empSecLevel);
jtaDisplay.setText("Employee number: " + decNum +
"\nEmployee name: " + decName + " " + decSname +
"\nSecurity clearance: " + decSecLevel);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
How can I get the code in the while statement to execute and display data in the JTextArea?
only if you have record ,it will come into while loop.Better use preparedstatement for dynamic value setting.For debugging purpose try to print your query in debugging and copy the query and execute in sql tool for checking whether any records.

Prepared Statement setString adding unnecessary single quotes to String

Background
I am trying to set the contents of an ArrayList into an IN clause in a Db2 SQL statement. I am using the PreparedStatement to build my query. This is our coding standard.
What I tried #1
I researched a couple ways to achieve this. I first tried using the setArray() as show in this question: How to use an arraylist as a prepared statement parameter The result was I was getting a error of Err com.ibm.db2.jcc.am.SqlFeatureNotSupportedException: [jcc][t4][10344][11773][3.65.110] Data type ARRAY is not supported on the target server. ERRORCODE=-4450, SQLSTATE=0A502 After this roadblock, I moved on to #2
What I tried #2
I then tried using the Apache Commons StringUtils to convert the ArrayList into a comma separated String like I needed for my IN clause. The result is that this did exactly what I needed, I have a single String with all my results separated by a comma.
The problem:
The setString() method is adding single quotes to the beginning and end of my String. I have used this many times, and it has never done this. Does anyone know if there is a way around this, or an alternative using the PreparedStatement?? If I use String concatenation my query works.
Code (explained above):
List<String> selectedStatuses = new ArrayList<String>(); //Used to store contents of scoped var
//Get Contents of Checkbox which are in the form of a List
selectedStatuses = (List) viewScope.get("selectedStatuses");
String selectedStatusesString = StringUtils.join(selectedStatuses, ",");
.... WHERE ATM_DET_ATM_STAT IN (?)";
ps.setString(1, selectedStatusesString);
Log Value showing correct value of String
DEBUG: selectedStatusesString: 'OPEN','CLOSED','WOUNDED','IN PROGRESS'
Visual of incorrect result
The quotes at the beginning and end are the problem.
For an IN clause to work, you need as many markers as you have values:
String sql = "SELECT * FROM MyTable WHERE Stat IN (?,?,?,?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "OPEN");
stmt.setString(2, "CLOSED");
stmt.setString(3, "WOUNDED");
stmt.setString(4, "IN PROGRESS");
try (ResultSet rs = stmt.executeQuery()) {
// use rs here
}
}
Since you have a dynamic list of values, you need to do this:
List<String> stats = Arrays.asList("OPEN", "CLOSED", "WOUNDED", "IN PROGRESS");
String markers = StringUtils.repeat(",?", stats.size()).substring(1);
String sql = "SELECT * FROM MyTable WHERE Stat IN (" + markers + ")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
for (int i = 0; i < stats.size(); i++)
stmt.setString(i + 1, stats.get(i));
try (ResultSet rs = stmt.executeQuery()) {
// use rs here
}
}
Starting with Java 11, StringUtils is no longer needed:
String markers = ",?".repeat(stats.size()).substring(1);
Use two apostrophes '' to get a single apostrophe on DB2, according to the DB2 Survival Guide. Then call .setString().
To anyone else experiencing the issue with single quotes, I had to modify my function so that it doesn't use ? to set the value; instead, I just treat the entire query as a string:
public static void runQuery(String tableName, String columnName, int value, String whereName, String whereValue) {
try (Connection con = DatabaseConnection.getConnection()) {
try (PreparedStatement ps = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + " = " + value + " WHERE " + whereName + " = " + "'" + whereValue + "'")) {
ps.executeUpdate();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
Hope this helps

How to select the last row of database in jsp?

I am not able to display the last row of my database in jsp. I already tried to print rs.getString(1), but it does not work.
ResultSet rs = st.executeQuery("Select MAX(CustomerID) from Customer");
while(rs.next()){out.print(rs.getString(1));}
I don't know if this is what you want but if you are trying to get the whole row there are some ways to accomplish that
ResultSet rs = st.executeQuery("select max(customerid) as id from customer");
rs.next();
String id = rs.getString("id");
rs = st.executeQuery("select field_a, field_b from customer where customerid = " + id);
rs.next();
String row = id + "," + rs.getString("field_a") + "," + rs.getString("field_b");
out.println(row);
Of course you need to replace the field_a and field_b columns with the ones in your customer table and add or remove columns according to your needs.
The shorter way is using order by and limit keywords like this
ResultSet rs = st.executeQuery("select customerid, field_a, field_b from customer order by customerid desc limit 1");
rs.next();
String row = rs.getString("customerid") + "," + rs.getString("field_a") + "," + rs.getString("field_b");
out.println(row);
Be secure of add a primary key or unique constraint to the customerid column for improve the performance of the both methods.

Get the data from mysql rows and display them separately by the ResultSet in Java

I have a mysql table user which is consisted of id, name, password and email columns.
Is there a way to create some sort of query or java code that will print in my message dialog window all of the users names.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
String sql = "select * from user;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
val1 = rs.getString(2);
val2 = rs.getString(3);
}
value = val1 + " " + val2;
JOptionPane.showMessageDialog(null,value);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
This only prints the name and the surname of the first user from the table :(
I want to print them all one below another!
If I set rs.getString(5); - it gives me an error: column index out of range.
I suggest you avoid JOptionPane for this kind of code. Better to use some Frame (Swing) and display all of the users into a separate window.
The problem with your code is that variable value is lyiong outside of the loop (which must be btw while loop, as spencer said).
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
String sql = "select * from user;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
val = rs.getString(2) + " " + rs.getString(3);
value += val + " ";
}
JOptionPane.showMessageDialog(null,value);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
Try to avoid this type of code, use ArrayList and save in the array all of the users credentials. Then easily label it wherever you want.
You're only fetching the first row from the resultset. It sounds like you want a loop, and process every row from the resultset.
while (rs.next()) {
}
UPDATE
Q: It only gives me now the last user. Probably because it overwrites the val1 and val2 variable. I suppose somehow this should also goes into the loop..
A: Yes, it should go inside the loop. But I'd be populating a collection, rather than concatenating a String.
As a performance and maintenance note, you can avoid the messiness of the string concatenation in the Java by doing the concatenation in the SQL statement. I wouldn't use SELECT * and rely on the positions of two particular columns in the resultset.
I'd use a SQL statement like this:
SELECT CONCAT(u.first_name,' ',u.last_name) AS user_name FROM users
If I wasn't populating a collection, and I needed to concatenate a honkous string, I'd use a StringBuffer, e.g.
val = new StringBuffer(4096));
while (rs.next()) {
val.append(rs.getString("user_name"));
}
value = val.toString;

SQL Where Clause with Values Provided

I am trying to use a SQL Select statement for a query in Java. I currently have the following:
ResultSet rs = stmt.executeQuery("SELECT *" +
" FROM " + table +
" WHERE " + selection +
" VALUES " + selectionArgs);
where "selection" is a string and "selectionArgs" is a string array.
String selection = "documentFK=?";
String[] selectionArgs = { ... };
Is it possible to use the VALUES command to replace the ? like in with the INSERT command? Either way, what would be the correct syntax?
Thanks for the help.
I believe what you're looking for is the IN statement. Your query should look like this:
SELECT *
FROM table
WHERE documentFK IN ('doc1', 'doc2', 'doc3')
AND userFK IN ('user1', 'user2', 'user3')
This is (obviously) going to make your code a bit more ugly. You'll have to ensure that the WHERE keyword is used for the first clause, but the AND keyword is used for every other clause. Also, each list will have to be comma-delimited.
no, that is not the way it's done. first you create the statement from the query, using the question marks as place holders for the real values you want to put there. then you bind these values to the statement.
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE documetFK = ?";
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the value
stmt.setInt(1, 4); //1 is "the first question mark", 4 is some fk
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
now, if you want this thing with selection string and some args, then you're going to have a loop in your java code. not sure what your array looks like (you're not giving me that much to go on), but if it's made up from strings, it would be something like this:
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE " + selection;
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the values
for(int i = 0; i < selectionArgs.length; i++) {
stmt.setString(i, selectionArgs[i]); //i is "the nth question mark"
}
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
Can you use a PreparedStatement?
First of all SELECT .. WHERE .. VALUES is incorrect SQL syntax. Lose the VALUES part.
Then you're looking for prepared statements.
In your example it's going to look something like this:
String sql = "SELECT * FROM myTable WHERE documentFK=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
ResultSet rs = pstmt.executeQuery();
Or with multiple parameters:
String sql = "SELECT * FROM myTable WHERE documentFK=? AND indexTerm=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
pstsm.setInt(2, 100); // assume indexTerm can be 100 and is an integer
ResultSet rs = pstmt.executeQuery();
However, all of this doesn't worth your while since you can simply do the same by concatenating the value into the statement. But be aware of the SQL injections, so don't forget to escape the parameters that you're passing into the database.
PS: I was typing this way too long. You already have the answers :-)
As a side note, you may want to take a look at this to prevent SQL injections:
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
Sormula can select using "IN" operator from a java.util.Collection of arbitrary size. You write no SQL. It builds the SQL SELECT query with correct number of "?" parameters. See example 4.

Categories