I'm sure this should be easy but I've been stucked for hours without understanding what's really happening in this code:
private void loadUnits() {
units = new ArrayList<Unit>(); //units is a class global variable
families = new ArrayList<Family>(); //families is a class global variable
Statement st;
Statement stFields;
ResultSet rs;
ResultSet rsFields;
try {
//Load units info
st = cnnSrc.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery(Queries.qUnits);
while (rs.next()) {
units.add(new Unit(rs));
}//END_WHILE
ConnectionProvider.close(rs, st);
//First load fields info
stFields = cnnSrc.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rsFields = stFields.executeQuery(Queries.qFields);
//Now load the Family information and create their instances
st = cnnSrc.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery(Queries.qFamily);
while (rs.next()) {
families.add(new Family(rs, rsFields, units));
this.debugGlobalParams();
}//END_WHILE
ConnectionProvider.close(rsFields, stFields);
ConnectionProvider.close(rs, st);
} catch (SQLException ex) {
LOGGER.error(ex.getMessage(), ex);
}//END_TRYCATCH
}//END_METHOD
public void debugGlobalParams() {
int n = units.size();
int nu = 0;
String unitNames = "";
LOGGER.debug("Debugging " + n + " Units");
for (int i = 0; i < n; i++) {
LOGGER.debug(units.get(i).getParkUnitTitleAersa());
}
n = families.size();
LOGGER.debug("Debugging " + n + " Families");
Family f;
for (int i = 0; i < n; i++) {
f = families.get(i);
LOGGER.debug("FamilyId = " + f.getFamilyId() + "; FamilyTitle = " + f.getFamilyTitle() + "; Tabla = " + f.getTabla());
nu = f.getUnits().size();
for (int j = 0; j < nu; j++) {
unitNames = unitNames + f.getUnits().get(j).getParkUnitTitleAersa() + ",";
}
LOGGER.debug("Units included => " + unitNames);
}
}//END_METHOD
This method is called once to get from DB my simple domain model, which should contain some Family descriptions and Unit descriptions as well. Each Unit should belong to one, and only one Family, and that association is done during the second while where I'm creating a new Family instance. The Unit constructor method is trivial, but for you to know the most relevant code on the Family constructor:
public Family(ResultSet rs, ResultSet rsFields, ArrayList<Unit> uns) {
try {
//Some local variables assignment...
units = new ArrayList<Unit>();
int n = uns.size();
for(int i=0; i<n; i++){
if(uns.get(i).getFamilyId() == this.FamilyId){
this.units.add(uns.get(i));
}
}//END_FOR
} catch (SQLException ex) {
LOGGER.error(ex.getMessage(), ex);
}//END_TRYCATCH
}//END_METHOD
Now, the problem is that the association between Family and their proper units is not done properly and when I call this.debugGlobalParams() I find that each Family is not only getting their units but also the previous family's units.
For example, if I have as families f1, f2 and f3 and each of them has three units u11, u12, u13, u21, u22, u23, u31, u32, u33 (where the first number indicates the family it should be associated with), I should be getting:
f1 -> u11, u12, u13
f2 -> u21, u22, u23
f3 -> u31, u32, u33
But instead I get this:
f1 -> u11, u12, u13
f2 -> u11, u12, u13, u21, u22, u23
f3 -> u11, u12, u13, u21, u22, u23, u31, u32, u33
I'm sure the problem is with the references but I don't understand why.... Anybody some ideas?
Thanks!!
The Problem is your debug display code. You put all unit names from one family into unitNames, but do not reset this String. Quick hack would be to reset the String:
n = families.size();
LOGGER.debug("Debugging " + n + " Families");
Family f;
for (int i = 0; i < n; i++) {
unitNames = ""; // <----------- ADD THIS LINE
f = families.get(i);
LOGGER.debug("FamilyId = " + f.getFamilyId() + "; FamilyTitle = " + f.getFamilyTitle() + "; Tabla = " + f.getTabla());
nu = f.getUnits().size();
for (int j = 0; j < nu; j++) {
unitNames = unitNames + f.getUnits().get(j).getParkUnitTitleAersa() + ",";
}
LOGGER.debug("Units included => " + unitNames);
}
A better solution would be to use iterators or Iterables, and declare the variable inside the loop:
for (Family f : families) {
LOGGER.debug("FamilyId = " + f.getFamilyId() + "; FamilyTitle = " + f.getFamilyTitle() + "; Tabla = " + f.getTabla());
String unitNames = "";
for (Unit unit : f.getUnits() {
unitNames = unitNames + unit.getParkUnitTitleAersa() + ",";
}
}
Related
I am trying to replace each instance of what is between two brackets using a loop and an array. array1a and array1b are the indices of where the brackets open and close. I want to get the number between the two brackets and increment it by one and replace the value currently there, but as the string text is currently a list (such as "list item (0) list item (10) list item (1023)" I want to use a loop to increment the value of each rather than to set all the values within brackets to the same value. I hope this makes sense!
String text = myString.getText();
for (int x = 0; x < 10; x++) {
array2[x] = text.substring(array1a[x], array1b[x]);
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
String text2 = text.replaceAll("\\(.*\\)", array3[x]);
myString.setText(text2);
}
Full Code:
public class CreateVideoList extends JFrame implements ActionListener {
JButton play = new JButton("Play Playlist");
JButton addVideo = new JButton("Add Video");
TextArea playlist = new TextArea(6, 50);
JTextField videoNo = new JTextField(2);
private int x = 0;
#Override
public void actionPerformed(ActionEvent e) {
String key = videoNo.getText();
String name = VideoData.getName(key);
String director = VideoData.getDirector(key);
Integer playCount = VideoData.getPlayCount(key);
String text = playlist.getText();
String rating = CheckVideos.stars(VideoData.getRating(key));
String output = name + " - " + director + "\nRating: "
+ rating
+ "\nPlay Count: " + playCount;
String newItem = key + " " + name + " - " + director + " ("
+ playCount + ") " + "\n";
String addToList = "";
String[] array3 = new String[100];
if ("Add Video".equals(e.getActionCommand())) {
if (Character.isDigit(text.charAt(0)) == false) {
playlist.setText("");
}
if (addToList.indexOf(key) == -1) {
addToList += addToList + newItem;
playlist.append(addToList);
array3[x] = key;
x++;
} else if (addToList.indexOf(key) != -1) {
JOptionPane.showMessageDialog(CreateVideoList.this,
"This video is already in the playlist. Please select a"
+ " different video.", "Add to playlist error", JOptionPane.INFORMATION_MESSAGE);
}
}
if ("Play Playlist".equals(e.getActionCommand())) {
Integer length = (text.length());
int counta = 0;
Integer[] array1a = new Integer[100];
Integer[] array1b = new Integer[100];
String strPlayCount = "";
for (x = 0; x < length; x++) {
if (text.charAt(x) == '(') {
counta++;
array1a[counta - 1] = x;
array1a[counta - 1] = array1a[counta - 1] + 1;
}
if (text.charAt(x) == ')') {
array1b[counta - 1] = x;
array1b[counta - 1] = array1b[counta - 1];
}
}
String[] array2 = new String[counta];
String[] array4 = new String[100];
for (int y = 0; y < counta; y++) {
array2[y] = text.substring(array1a[y], array1b[y]);
array2[y] = array2[y] + 1;
playCount = Integer.parseInt(array2[y]);
array4[y] = "(" + array2[y] + ")";
String text2 = text.replaceAll("\\(.*\\)", array4[y]);
playlist.setText(text2);
}
}
}
Replace
array2[x] = array2[x] + 1;
array3[x] = "(" + array2[x] + ")";
with
Integer n = Integer.parseInt(array2[x]) + 1;
array3[x] = "(" + n.toString() + ")";
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I would appreciate if someone here could help me making some changes in the code below in order to play the game only those whose name starts with every letter except the A or a letter. Here is the code:
public void setupPlayers() {
checkValidPlayer();
playerNames = new String[nPlayers];
for (int i = 0; i < nPlayers; i++) {
playerNames[i] = JOptionPane.showInputDialog("Jepni emrin e lojtarit " + (i + 1));
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "A jeni te regjistruar?", "Regjistrohu?",
dialogButton);
if (dialogResult == 0) {
String enteredName = playerNames[i];
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager
.getConnection("jdbc:ucanaccess://C:\\Users/USER/Downloads/javaDB.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM LOJTAR ");
List<String> dbName = new ArrayList<>();
List<String> dbSurname = new ArrayList<>();
while (rs.next()) {
// Retrieve by column name
dbName.add(rs.getString("Emri"));
dbSurname.add(rs.getString("Mbiemri"));
}
int k = 0;
int a = 0;
while (k < dbName.size()) {
if (dbName.get(k).equals(enteredName)) {
a = 1;
break;
}
k++;
}
if (a == 1) {
if (enteredName.charAt(0) != 'a' || enteredName.charAt(0) != 'A') {
ResultSet rs1 = s
.executeQuery("SELECT ID FROM LOJTAR WHERE Emri = '" + enteredName + "'");
int lojtarID = 0;
while (rs1.next()) {
lojtarID = rs1.getInt("ID");
}
ResultSet rs2 = s.executeQuery("SELECT * FROM PIKET WHERE ID = '" + lojtarID + "'");
List<Integer> dbPiket = new ArrayList<>();
while (rs2.next()) {
// Retrieve by column name
dbPiket.add(rs2.getInt("Piket"));
}
int j;
int n = dbPiket.size();
int[] vektoriPikeve = new int[n];
for (j = 0; j < n; j++) {
vektoriPikeve[j] = dbPiket.get(j);
}
JOptionPane.showMessageDialog(null,
"U identifikuat me sukses. Ju jeni " + dbName.get(k) + " " + dbSurname.get(k)
+ " dhe keni sipas hereve piket e meposhteme: \n"
+ Arrays.toString(vektoriPikeve));
} else {
JOptionPane.showMessageDialog(null,
"Ju dhate nje emer qe fillon me A. Ju lutem jepni nje emer tjeter!");
playerNames[i] = JOptionPane.showInputDialog("Jepni emrin e lojtarit " + (i + 1));
}
}
else {
JOptionPane.showMessageDialog(null,
"Emri juaj nuk u gjet ne bazen tone te te dhenave ose fillon me shkronjen A. Ju lutem regjistrohuni!");
registerPlayers();
}
// close and cleanup
s.close();
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
else {
registerPlayers();
}
}
}
Thank you in advance!
What changes do you really want to make? You can make use of this change String methods to check your enteredname
if(!(enteredname.toLowerCase().startsWith("a"))){
// do something or play
}
I have been facing some trouble with memory management. I have some code here that runs an sql query in a loop, puts the data into Array Lists and then does some computations. I have run many similar programs before without this problem. The reason I put the query in a loop was so that too much memory wouldn't be stored in java objects at once. However, now when I run the program, I get a memory error at the exact same place every time (when it is at the 29th iteration of the loop).
Here is the error -
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at transnMat.bootTrnsn.main(bootTrnsn.java:82)
I have pasted the code below, I'd really appreciate any tips on what I might change to get rid of this -
Connection conn = null;Statement st = null;ResultSet rstru = null;
for(int i=start;i<stop;i++) {
double[][] forvariance = new double[(demos.length-1)][numsims];
ArrayList<Long> hhids1 = new ArrayList<>();
ArrayList<Double> outlierwt = new ArrayList<>();
ArrayList<String> fbdemos = new ArrayList<>();
ArrayList<String> trudemos = new ArrayList<>();
rstru = st.executeQuery(
"select TRUTH_DEMO_ID, FB_DEMO_ID, RN_ID, OUTLIER_WEIGHT from SCRATCH.." +
months + "monthtable where BRAND_ID = " + brands[i] +
" order by RN_ID");
while (rstru.next()) { //Get query results and put them into a hash map.
String temp0 = rstru.getString(1);
String temp1 = rstru.getString(2);
String temp2 = rstru.getString(3);
String temp3 = rstru.getString(4);
//String temp5 = rstru.getString(6);
hhids1.add(Long.parseLong(temp2.substring(0,11)));
fbdemos.add(temp1);
trudemos.add(temp0);
outlierwt.add(Double.parseDouble(temp3));
}
for(int sim=0;sim<numsims;sim++) {
trnsnpv = new double[demos.length][demos.length-1];
HashMap<Long,Integer> thissampl = bootsampl2.get(sim);
for(int i1=0;i1<fbdemos.size();i1++) {
if(thissampl.containsKey(hhids1.get(i1)))
trnsnpv[dems.get(fbdemos.get(i1))][dems.get(trudemos.get(i1))-1] +=
outlierwt.get(i1)*(double)thissampl.get(hhids1.get(i1));
}
for(int j=0;j<trnsnpv.length;j++) { //27 rows
trnsnpv[j] = normalize(trnsnpv[j]);
for(int k=0;k<trnsnpv[j].length;k++) { //26 columns
forvariance[k][sim] += trnsnpv[j][k];
}
}
}
for(int k = 0; k < (demos.length - 1); k++) {
double d = StdStats.var11(forvariance[k]);
fileIO.fileIO.write2file(brands[i] + "," + demos[k+1] +
"," + String.valueOf(d) + "\n", "vars.csv");
}
System.out.println("Brands processed: " + String.valueOf(i-start) +
" out of: " + (stop-start));
hhids1.clear();
outlierwt.clear();
fbdemos.clear();
trudemos.clear();
}
Several performance problems here:
The database has to recompile the query each time because the SQL is not parameterized. Consider the use of a prepared statement.
Nested loops. I see one point where you have 4 nested loops.
There is no way I can figure out what your logic is doing due to the variable names and excessive looping. If it's possible, and not sure if it is with your logic (depends on what aggregation you are doing), can you do everything one object at a time in your while (rs.next()) loop?
Ex:
while (rs.next()) {
String temp0 = rstru.getString(1);
String temp1 = rstru.getString(2);
String temp2 = rstru.getString(3);
String temp3 = rstru.getString(4);
//String temp5 = rstru.getString(6);
// do all of your work in here, so that your objects
// can be garbage collected before the next iteration
}
Here is the version of the code that did work (for my own reference)..
for(int i=start;i<stop;i++){
double[][] forvariance = new double[(demos.length-1)][numsims];
trnsnpv = new double[numsims][demos.length][demos.length-1];
int size = 0;
Long hhids1;
Double outlierwt;
String fbdemos;
String trudemos;
rstru = st.executeQuery("select TRUTH_DEMO_ID, FB_DEMO_ID, RN_ID, OUTLIER_WEIGHT from SCRATCH.."+months+"monthtable where BRAND_ID = " + brands[i]+" order by RN_ID");
while (rstru.next()) {//Get query results and put them into a hash map.
String temp0 = rstru.getString(1);String temp1 = rstru.getString(2);String temp2 = rstru.getString(3);String temp3 = rstru.getString(4);
hhids1 = (Long.parseLong(temp2.substring(0,11)));
fbdemos = (temp1);
trudemos = (temp0);
outlierwt = (Double.parseDouble(temp3));
for(int sim=0;sim<numsims;sim++){
HashMap<Long,Integer> thissampl = bootsampl2.get(sim);
if(thissampl.containsKey(hhids1))
trnsnpv[sim][dems.get(fbdemos)][dems.get(trudemos)-1] += outlierwt*(double)thissampl.get(hhids1);
}
size++;
}
System.out.print("Processing: " + size + " rows");
for(int sim=0;sim<numsims;sim++){
for(int j=0;j<trnsnpv[sim].length;j++){//27 rows
trnsnpv[sim][j] = normalize(trnsnpv[sim][j]);
for(int k=0;k<trnsnpv[sim][j].length;k++){//26 columns
forvariance[k][sim] += trnsnpv[sim][j][k];
}
}
}
for(int k = 0; k < (demos.length - 1); k++){
double d = StdStats.var11(forvariance[k]);
fileIO.fileIO.write2file(brands[i] + "," + demos[k+1] + "," + String.valueOf(d) + "\n", "vars.csv");
}
System.out.print("Brands processed: " + String.valueOf(i-start + 1 ) + " out of: " + (stop-start) + "\n");
//hhids1.clear();outlierwt.clear();fbdemos.clear();trudemos.clear();
}
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);
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]);