Here is a method that I am writing for a class. It is supposed to refresh a table with data obtained from quering a database. I get an error when trying to scan through the line newResult.next().
I tried debugging, but that doesn't show me anything. the code prints out the line "In while loop", so I know that the problem is the in the line right after it. I constantly get the error, "After start of result set". I tried looking at my code, but it doesn't look like I am calling that method anywhere else either. thanks.
public void refresh()
{
try
{
Statement statement = gtPort.getConnection().createStatement();
//this query is also not working, not really sure how it works.
String query = "SELECT CRN, Title, Instructor, Time, Day, Location, Letter"
+ "FROM Section S WHERE CRN NOT IN "
+ "(SELECT CRN FROM Registers R WHERE Username = \""
+ gtPort.userName + "\")";
System.out.println(query);
statement.executeQuery(query);
System.out.println("Statemetne execute ");
// String[] columns = {"Select", "CRN", "Title", "Instructor", "Time",
// "Days", "location", "Course Code*", "Section"*,"Mode of Grading*"};
ResultSet result = statement.getResultSet();
System.out.println("created result");
data = new Object[10][10];
System.out.println("created data");
Object[] values = new Object[10];
System.out.println("created values");
// values[0] = null;
if (result == null)
{
System.out.println("result is null");
}
String[] titles = new String[100];
//for (int i = 1; i< table.getColumnCount(); i++)
//model.removeRow(i);
//table.removeAll();
//table.repaint()
model.setRowCount(0);
table = new JTable(model);
model.setRowCount(35);
for (int i = 1; result.next(); i++)
{
values[1] = Boolean.FALSE;
for (int j = 2; j< 8; j++)
values[j] = result.getString(j);
titles[i] = result.getString(2);
model.insertRow(i, values);
}
String[] codes = new String[table.getColumnCount()];
System.out.println("count: " + titles.length);
for (int i = 1; I < titles.length; i++)
{
query = new String("SELECT C.Code FROM Code C WHERE C.Title = \""
+ titles[i] + "\"");
//this is a different query to check for titles.
statement.executeQuery(query);
System.out.println(query);
ResultSet newResult = statement.getResultSet();
// codes[i] = newResult.getString(1);
if (newResult == null)
{
System.out.println("it is null");
break;
}
//this is the loop where it breaks.
while(newResult.next());
{
System.out.println("in while loop");
//this line prints, so the next line must be the problem.
model.setValueAt(newResult.getString(1), i, 8);
}
System.out.println("nr: \t" +newResult.getString(1));
}
System.out.println("before table");
table = new JTable(model);
System.out.println("created table");
}
catch (Exception exe)
{
System.out.println("errored in course selection");
System.out.println(exe);
}
}
Write ResultSet rs = statement.executeQuery(query); instead. getResultSet() is called when you have got more then one result sets from executed statement.
Don't use constructor new String() for creating String. Simply write:
String new = "content";
You cannot predict how much your first query will return so don't create arrays with stated size but use better ArrayList:
Code:
//creation
List<Object> values = new ArrayList<Object>();
List<String> titles = new ArrayList<String>();
//usage - adding
values.add(someObject);
//usage - getting
for (String title : titles)
//or
titles.get(byIndex);
Related
Hi I have an arraylist of strings, I want to show the content of the arraylist on JLabel separated by a space or comma. But it shows me only one String, the last one.
public void ShowMovie(int idMovie) throws SQLException, IOException {
int ID = idMovie;
String IDMOVIE = Integer.toString(ID);
IDMovieLabel.setText(IDMOVIE);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Cover.class.getName()).log(Level.SEVERE, null, ex);
}
con = DriverManager.getConnection("jdbc:mysql://localhost/whichmovie", "Asis", "dekrayat24");
String sql = "SELECT Title,Year,Country,recomendacion,Cover,Rating,NameDirec,Name FROM movie "
+ "Inner join direction on (movie.idMovie=direction.idMovie5)"
+ "Inner join director on (direction.idDirector=director.idDirector)"
+ "Inner join cast on (movie.idMovie=cast.idMovie4)"
+ "Inner join actor on (cast.idActor=actor.idActor)"
+ "where idMovie= '" + ID + "'";
st = con.prepareStatement(sql);
rs = st.executeQuery(sql);
while (rs.next()) {
String titulo = rs.getString(1);
int añoInt = rs.getInt(2);
String año = Integer.toString(añoInt);
byte[] imagedataCover = rs.getBytes("Country");
byte[] imagedataCover1 = rs.getBytes("Cover");
format = new ImageIcon(imagedataCover);
format2 = new ImageIcon(imagedataCover1);
TituloLabel.setText(titulo);
AñoLabel.setText(año);
CountryLabel.setIcon(format);
DirectorLabel.setText(rs.getString(7));
int Recomend = rs.getInt(4);
String Recom = Integer.toString(Recomend);
RecommendLabel.setText(Recom);
int Rating = rs.getInt(6);
String Rat = Integer.toString(Rating);
RatingLabel.setText(Rat);
starRater1.setSelection(Rating);
starRater1.setEnabled(false);
Image imgEscalada = format2.getImage().getScaledInstance(CoverLabel.getWidth(),
CoverLabel.getHeight(), Image.SCALE_SMOOTH);
Icon iconoEscalado = new ImageIcon(imgEscalada);
CoverLabel.setIcon(iconoEscalado);
ArrayList<String> actors = new ArrayList<>();
actors.add(rs.getString(8));
System.out.println(actors);// Here i can see i get 9 actors.
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : actors) {
if (!first) {
sb.append(' ');
}
sb.append(s);
first = false;
}
CastLabel1.setText(sb.toString());
}
rs.close();
st.close();
con.close();
}
Any help ?
Edit:unfortunately no solution has helped me, maybe I'm doing something wrong in the method, I post the full method.
String text = "";
for(int i = 0; i < actors.size(); i++){
text = text + actors.get(i);
if(i < actors.size() - 2){
text = text + ", ";
}
}
CastLabel1.setText(text);
The problem is you are resetting the label for each step in the for loop, and not creating a cumulative result. See below:
StringBuilder buf = new StringBuilder();
for(int i = 0; i < actors.size(); i++){
buf.append(actors.get(i));
if(i < actors.size() -1){
buf.append(" ");
}
}
CastLabel1.setText(buf.toString())
You should build the string you want to show first then set it to the text of the label:
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : actors) {
if (!first)
sb.append(' ');
sb.append(s);
first = false;
}
CastLabel1.setText(sb.toString());
What you're currently doing is changing the entire label text during each iteration, so the final text is that of the last element in the list.
I have following codes:
-------class------------
private class SystemHealthAlert implements Work {
List<MonitorAlertInstance> systemHealthAlertList;
private String queryString;
// private java.util.Date startDate;
// private java.util.Date endDate;
#Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(queryString);
int index = 1;
ResultSet rs = ps.executeQuery();
int columnCount = rs.getMetaData().getColumnCount();
while(rs.next())
{
//String[] row = new String[columnCount];
//results.set(index, element);
//for (int i=0; i <columnCount ; i++)
// {
// row[i] = rs.getString(i + 1);
// }
systemHealthAlertList.add(row);
}
rs.close();
ps.close();
}
}
---------Method-----------
public List<MonitorAlertInstance> getSystemHealthAlert(Long selectedSensorId) {
List<MonitorAlertInstance> systemHealthAlertList;
try {
// Add SELECT with a nested select to get the 1st row
String queryString = "select min(MONITOR_ALERT_INSTANCE_ID) as MONITOR_ALERT_INSTANCE_ID, description" +
" from ems.monitor_alert_instance " +
" where description in (select description from monitor_alert_instance" +
" where co_mod_asset_id = " + selectedSensorId +
" )" +
" group by description";
SystemHealthAlert work = new SystemHealthAlert();
// work.coModAssetId = coModAssetId;
work.queryString = queryString;
getSession().doWork(work);
systemHealthAlertList = work.systemHealthAlertList;
} catch (RuntimeException re) {
// log.error("getMostRecentObservationId() failed", re);
throw re;
}
//log.info("End");
return systemHealthAlertList;
}
My query returns three rows from DB. How can I return systemHealthAlertList from the class that will have all the three rows of the query.
In method execute, you should fill your List<MonitorAlertInstance> systemHealthAlertList with instances of MonitorAlertInstance. Create a new instance of MonitorAlertInstance inside the while loop where you retrieve the data:
//You don't need this line, remove it
//int columnCount = rs.getMetaData().getColumnCount();
while(rs.next()) {
//create a new instance of MonitorAlertInstance per ResultSet row
MonitorAlertInstance monitor = new MonitorAlertInstance();
//set the fields from the ResultSet in your MonitorAlertInstance fields
//since I don't know the fields of this class, I would use field1 and field2 as examples
monitor.setField1(rs.getInt(1));
monitor.setField2(rs.getString(2));
//and on...
systemHealthAlertList.add(monitor);
}
Apart from this problem, you should initialize your List<MonitorAlertInstance> systemHealthAlertList variable before use it:
systemHealthAlertList = new ArrayList<MonitorAlertInstance>();
while(rs.next()) {
//content from previous code...
}
Define a class/bean to hold the data from one given row. Loop through your rows, and create one instance of that class for each row you have. Add these instances to some List. Return the List of these 3 instances.
I have a problem regarding my JTable, I don't know how can I store my fetch records which is of type String from my database to the multidimensional array which is let's say Object[][] data. What I want to do is show my database records to the JTable, I already fetch the records in dtabase and store it in my String variables, The question is how can I store the fetch records to the multidimensional array of Object and use it on my JTable.
Here are my code for fetching records:
static class TableData{
Object[][] data;
int count = 0;
Statement sql = null;
String query, user = "JEROME", pass = "Perbert101", driver = "oracle.jdbc.OracleDriver", conString = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
Connection con = null;
ResultSet rs = null;
TableData(){
try{
Class.forName(driver);
}
catch(ClassNotFoundException e){
JOptionPane.showMessageDialog(null, "Problem Loading Driver");
}
try{
con = DriverManager.getConnection(conString, user, pass);
sql = con.createStatement();
sql.executeQuery("SELECT * FROM INVENTORY");
rs = sql.getResultSet();
int key = 0;
String val = null, val1 = null, val2 = null, val3 = null, val4 = null, val5 = null;
System.out.println("Results: ");
while(rs.next()){
key = rs.getInt(1);
if(rs.wasNull()){
key = -1;
}
val = rs.getString(2);
if(rs.wasNull()){
val = null;
}
val1 = rs.getString(3);
if(rs.wasNull()){
val = null;
}
val2 = rs.getString(4);
if(rs.wasNull()){
val = null;
}
val3 = rs.getString(5);
if(rs.wasNull()){
val = null;
}
val4 = rs.getString(6);
if(rs.wasNull()){
val = null;
}
val5 = rs.getString(7);
if(rs.wasNull()){
val = null;
}
System.out.println("Key = " + key);
System.out.println("value = " + val);
System.out.println("value = " + val1);
System.out.println("value = " + val2);
System.out.println("value = " + val3);
System.out.println("value = " + val4);
System.out.println("value = " + val5);
}
sql.close();
con.close();
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, "Error Loading Database Data");
}
}
}
//----------END------------
public static void main(String[] args){
POSModel.TableData data = new POSModel.TableData();
}
I'd suggest that the data you're pulling from the database needs to be stored in an array (by columns) first...
Object[] rowData = new Object[7];
rowData[0] = key;
rowData[1] = val;
rowData[2] = val1;
rowData[3] = val2;
rowData[4] = val3;
rowData[5] = val4;
rowData[6] = val5;
This then needs to be stored in some kind of row structure, I'd personally use a List. The main reason for this choice is that you probably don't know in advance the number of rows you will be reading...
List<Object[]> rowList = new ArrayList<Object[]>(25);
// Process the resultset...
// Create the column array from above...
rowList.add(rowData);
Once you've completed reading all the rows, you need to convert the list it an array...
data = rowList.toArray(new Object[](rowList.size())); // I like to provide my own array
Equally, you could do...
data = new Object[rowList.size()][7];
rowList.toArray(data);
Which ever is more convenient...
Now you should have a 2D array...
I have a webservice where from the Client-side some parameters are passed to perform a query on the DB, the Server-Side is supposed to carry out the query and return the results.Since the result might be more than one row and i will have to use it on the client-side to show an output this what i did:
1.Perform the query
2.take each row of the result and put it in an array
3.convert the array to String and pass it to the client side(converted array to String, because it was simple)
BUT the problem is that it doesnt pass the the array-turned-string but only the value which was used to initialize the string, here is the code
String ris = "";
String q;
String beta = null;
String one="";
String errore = connetti();
try {
if (errore.equals("")) {
Statement st = conn.createStatement();
//ESECUZIONE QUERY
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
}
//This is the part which i'm talking about
else {
//getRowCount is another class used to find out number of rows,I use it to declare an array which would contain the result of the query
int two=getRowCount(rs);
String[] alpha= new String[two];
//Loop through the resultstatement and put result from the column **nome** in the array **alpha**
while(rs.next()){
alpha[i]=rs.getString("nome");
i++;
}
//The value of ris which is empty, is returned
ris="";
//instead of this one, where i convert the array **alpha** to String
ris=arrayToString(alpha,",");
}
}
else {
ris = errore;
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
}
//returns the number of rows of **ris**
public static int getRowCount(ResultSet set) throws SQLException
{
int rowCount;
int currentRow = set.getRow(); // Get current row
rowCount = set.last() ? set.getRow() : 0; // Determine number of rows
if (currentRow == 0) // If there was no current row
set.beforeFirst(); // We want next() to go to first row
else // If there WAS a current row
set.absolute(currentRow); // Restore it
return rowCount;
}
//converts the array to String
public String arrayToString(String[] array, String delimiter) {
StringBuilder arTostr = new StringBuilder();
if (array.length > 0) {
arTostr.append(array[0]);
for (int i=1; i<array.length; i++) {
arTostr.append(delimiter);
arTostr.append(array[i]);
}
}
return arTostr.toString();
Thanks alot in advance!
After conn.close() you return beta instead of ris. This may be the cause of the behavior you are experiencing. However, I am not sure because I can not properly see how you open and close the curly brackets.
I query a database and get a lot information back that should be presented to the user. In the database I have fields a, b, c, d and e. Now, the user should be able to indicate which of these fields that should be printed on screen (i.e. the user can choose to view only a subset of the data retrieved from the database).
How do I dynamically create a print statement that sometimes prints two of the fields, sometimes four, sometimes three etc. depending on what the user wants?
If all the hard work is already done and you just have a result set to print, then it could be as simple as a succession of calls to System.out.print() for each result and then finish the line with a \n. It can be nested in a FOR loop, so if you have an int with the number of fields to print, just iterate through them.
In a more complicated case when you have a full list where some fields are chosen and others not, then you could use a (slightly) crude method like this:
...
String[] chosenFields = {"Field 1", "Field 2" /*, (et cetera) */};
for (int i = 0; i < numberOfFields; i++)
{
for (int j = 0; j < chosenFields.length; j++)
{
if (fieldsName[i].equals(chosenFields[j]))
System.out.print(fields[i] + " ");
break;
}
}
System.out.println();
...
Sorry about bad indentation; not sure how to sort it on here!
If field names are indeterminate at runtime and you're using Java to execute queries, consider using class ResultSetMetaData to get them.
EDIT:
As an example, here's some of my code which gets all the field names from a table, then creates a tickbox for each, which the user can select or deselect. All the JFrame GUI stuff I've omitted. When the user presses a submit button, the application check each tickbox and constructs an SQL statement to suit the users request.
...
JCheckBox[] jcb;
ResultSetMetaData rsmd;
private void makeCheckBoxes()
{
initConnection(); // Establish connection to MySQL server
try
{
Statement query = connection.createStatement();
ResultSet rs = query.executeQuery("SELECT * FROM client_db;");
rsmd = rs.getMetaData();
noOfColumns = rsmd.getColumnCount();
jcb = new JCheckBox[noOfColumns];
for (int i = 0; i < noOfColumns; i++)
{
jcb[i] = new JCheckBox(rsmd.getColumnName(i + 1));
jpCheckBoxes.add(jcb[i]);
jcb[i].setEnabled(false);
jcbComboBox.addItem(rsmd.getColumnName(i + 1));
}
jcb[0].setSelected(true);
rs.close();
query.close();
connection.close();
}
catch (SQLException e)
{
System.err.println("!> Caught SQLException:\n" + e.getMessage());
System.exit(1);
}
}
...
if (e.getSource() == jbSubmit)
{
String query = "";
initConnection();
if (jtfSearch.getText().isEmpty() == true) // JTextField
{
jtaResults.setText(null); // JTextArea
jtaResults.append("Please enter some search text in the text box above!\n");
return;
}
else
{
int selectedFields;
if (jrbAll.isSelected() == true) // JRadioButton
{
query = "SELECT *";
selectedFields = -1;
}
else
{
query = "SELECT";
selectedFields = 0;
for (int i = 0; i < noOfColumns; i++)
if (jcb[i].isSelected() == true)
{
try
{
if (selectedFields > 0)
query += ",";
query += " " + rsmd.getColumnName(i + 1);
}
catch (SQLException err)
{
System.err.println("!> Caught SQLException:\n" + err.getMessage());
System.exit(1);
}
selectedFields++;
}
}
if (selectedFields == 0)
{
jtaResults.setText(null);
jtaResults.append("No fields were selected!!\n");
return;
}
else
{
query += " FROM client_db WHERE " + jcbComboBox.getSelectedItem() + " LIKE '%" + jtfSearch.getText() + "%'";
if (jcbCurrentClients.isSelected() == true)
query += " AND currentClient LIKE 'y'";
query += ";";
}
}
System.out.println("Query = \"" + query + "\"");
/* Now, print it out in the text area!! */
try
{
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsMetaData = rs.getMetaData();
int columnCount = rsMetaData.getColumnCount();
jtaResults.append("--------------------------------\n");
int noOfResults = 0;
jtaResults.setText(null);
while (rs.next() == true)
{
if (noOfResults > 0)
jtaResults.append("\n");
jtaResults.append("* Search match " + (noOfResults + 1) + ":\n");
for (int i = 0; i < columnCount; i++)
{
jtaResults.append("-> " + rsMetaData.getColumnName(i + 1) + ": " +
rs.getString(i + 1) + "\n");
}
noOfResults++;
}
if (noOfResults == 0)
{
jtaResults.append("No results were returned; please try again with more ambiguous search terms.\n\n");
}
//scroller.setScrollPosition(0, 1048576);
rs.close();
stmt.close();
connection.close();
}
catch (SQLException err)
{
System.err.println("!> Caught SQLException:\n" + err.getMessage());
System.exit(1);
}
}
}
Hopefully this helps. The sustained concatenation to query forms a valid SQL statement based on the fields the user chose. Hopefully a few modifications to this to just print certain fields will help you. The System.out.println() call to print query about two-thirds down is a good place to work from.
The natural way to switch an optional value on or off would be a radiobutton. For 5 fields i.e. an array of 5 radiobuttons.
StringBuffer sb = new StringBuffer (5 * 10);
for (int i = 0; i < 5; ++i)
if (rb[i])
s.append (field[i]).append (" ");
Maybe you're better of only selecting interesting columns from the database? Then a dummy-column is helpful:
sql = new StringBuffer ("SELECT 1 "); // the dummy-column
for (int i = 0; i < 5; ++i)
if (rb[i])
sql.append (", ").append (fieldname[i]);