-2

I use MS SQL Server and Java with JDBC to connect. I don't know how to display the result of my simple SQL queries in a Java Texfield. Displaying my data in a JTable is no problem with the external JAR rs2xml.

That works and prints my table in the panel.

String MaxQuery = "SELECT * FROM Employees";
PreparedStatement pst=con.prepareStatement(MaxQuery);
ResultSet rs=pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));

But when i want to display a simple query like "SELECT AVG(budget) FROM Employees" with 1 result, i want to print this in a textfield.

The method setModel doesn't work with Textfields. So i have tried something like that:

String AVGQuery = "SELECT AVG(budget) FROM Employees";
PreparedStatement pst=con.prepareStatement(AVGQuery);
ResultSet rs=pst.executeQuery();
textFieldAns.setText(rs.toString());

But that prints me "SQLServerResultSet:1". I want the result, and not the number of results. Hope u can help me by my little problem :).

2

1 Answer 1

1

I believe you need to use code similar to

if (rs.next()) {
    textFieldAns.setText(rs.getString("column name you want to print");
}

Here is s good example https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html

Sign up to request clarification or add additional context in comments.

3 Comments

The problem is, there is no column name for this result. When i say "SELECT AVG(budget) FROM Employees" the column name is not defined.
You can specify the column by index, getString(int); just remember, in JDBC it's 1 indexed, not 0 indexed like the rest of the Java API
Thanks a lot! That was my problem. I do that hours ago, but i ever used 0...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.