I have a method that connects to and loads a database. It saves all of the usernames with scores into a ResultSet. At the moment, I can only get it to print separately to the console line by line. How could I save the whole ResultSet into a String so I can print this into a JTextField?
Model Class:
public static void loadDatabase() {
try {
getDb().connectDB();
getDb().createDB();
ResultSet rs = getDb().getScores();
while (rs.next()) {
System.out.print("Username: "+rs.getString(1));
System.out.println(" Score: "+rs.getString(2));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
Controller class:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == view.getSubmitButton()) {
Model.getDb().insertScores(view.getUsernameTextField().getText(), Model.getScore()); //insert scores into table
view.getInstructions().setText("Scores: ");
}
}
getInstructions() is a JTextArea. I would like this line:
view.getInstructions().setText("Scores: ");
to display the full list of scores
You can return a String in loadDatabase() with the text that you want:
public static String loadDatabase()
Inside, instead of printing to console, you just save those results to a String:
StringBuilder resultText = new StringBuilder();
while (rs.next()) {
resultText.append("Username: ").append(rs.getString(1)).append(" Score: ").append(rs.getString(2));
}
return resultText.toString();
You would then need to call loadDatabase() before view.getInstructions().setText("Scores: "); and add it to that setText.
Nothing simpler than that. Use a StringBuilder to concatenate Your string while iterating:
final StringBuilder builder = new StringBuilder();
while( rs.next() ) {
builder
.append("Username: ").append( rs.getString(1) )
.append( "Score: " ).append( rs.toString(2) )
;
}
String allResults = builder.toString();
But: Did you ask google before asking this question?
inside loadDatabase() :
Instead of
while (rs.next()) {
System.out.print("Username: "+rs.getString(1));
System.out.println(" Score: "+rs.getString(2));
}
You should put:
String[] arrayofScores = null;
while (rs.next()) {
String score= rs.getString(2);
arrayofScores = score.split("\n");
for (int i =0; i < arr.length; i++){
System.out.println(arrayofScores [i]);
}
}
Or you can use StringBuilder as #Alex GS suggested
Related
i have a small translation program to develop. The user input a sentence and the sentence is then check in a table in my database. if the sentence to sentence match is found. it displays the result else it removes the last word of the sentence and rechecks until a match is found or until one word is left( to be developed) . i have a small implementation for the handling of sentence to sentence match but i am having a small problem with my loop. i cannot figure out out to make it work. I know the problem is the the else part of loop i cannot figure out how to do it. I am not sure if the compiler will even loop back for the truncated sentence.
String sentence = "i am a good boy";
for(int j=0;j<sentence.length();j++)
{
if(sentence.length()>1)
{
sentence = lookUpSentencePart(sentence);
rs2 = sentenceDBQuery(sentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
System.out.println("mon pass dan rs1 true");
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
else
{
sentence = lookUpSentencePart(sentence);
rs2 = sentenceDBQuery(sentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
}
}
}
public String lookUpSentencePart(String sentence)
{
sentence = sentence.substring(0, sentence.lastIndexOf(" "));
return sentence;
}
public ResultSet sentenceDBQuery(String sentence, String source, String target)
{
ResultSet rs = null;
Statement stmt;
myConnection db = new myConnection();
try
{
Connection myConn = db.theconnect();
stmt = myConn.createStatement();
rs = stmt.executeQuery("SELECT " + target + " from sentence WHERE " + source + " = '" + sentence+"'");
}
catch(SQLException e)
{
e.printStackTrace();
}
return rs;
}
Probably you need smth like that :) You still need to add some boundary checks
String[] sentence = "i am a good boy".split(" ");
for(int j=0;j<sentence.length;j++)
{
String realSentence = buildSentence(sentence, j);
rs2 = sentenceDBQuery(realSentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
System.out.println("mon pass dan rs1 true");
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
}
public String buildSentence(String[] parts, int index) {
StringBuilder result = new StringBuilder();
for (int j = 0; j < (parts.length - index); j++) {
sb.append(parts[j]).append(" ");
}
sb.setLength(sb.length() - 1);
return result.toString();
}
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 try to generate random code name as licenseKey and check whether it is exist in database or not. If not exist, then display in my jsp page, if exist, continue generating the random code. I got the error "java.lang.StackOverflowError". How to solve this? Below is my code :
package com.raydar.hospital;
import com.raydar.hospital.DB_Connection;
import java.sql.*;
public class RandomCodeGenerator {
String licenseKey = "";
int noOfCAPSAlpha = 4;
int noOfDigits = 4;
int minLen = 8;
int maxLen = 8;
char[] code = RandomCode.generateCode(minLen, maxLen, noOfCAPSAlpha, noOfDigits);
public RandomCodeGenerator(){
}
public String getOutputCode() throws Exception{
String result ="";
result = isLicenseKeyExist();
System.out.println("4 + " +result);
if (result=="false"){
System.out.println("1 + " +new String(code));
licenseKey = new String(code);
}
else if (result=="true"){
System.out.println("2 + " +new String(code));
licenseKey = new String(code);
isLicenseKeyExist ();
}
return licenseKey;
}
private String isLicenseKeyExist () throws Exception{
String code = "";
code = getOutputCode();
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
String result="";
System.out.println("3 + " +code);
try{
DB_Connection connect = new DB_Connection();
connection = connect.getDBConnection();
statement = connection.createStatement();
rs = statement.executeQuery("SELECT licenseKey FROM hospital WHERE licenseKey = '" +code+ "'");
if (rs.next()){
result = "true";
}
else{
result = "false";
}
}catch (Exception e){
System.out.println("Error retrieving data! "+e);
}
return result;
}
}
You create a recursive loop where isLicenseKeyExist() calls getOutputCode(), but then getOutputCode() calls isLicenseKeyExist(). So eventually you run out of stack space, and get this exception.
Here,
public String getOutputCode() throws Exception{
String result ="";
result = isLicenseKeyExist();
...
}
private String isLicenseKeyExist () throws Exception{
String code = "";
code = getOutputCode();
...
}
I think you want something like this. Remove the field called code from your class, and its initialiser, and put the call to RandomCode.generateCode inside your getOutputCode method like this. The reason is that you'll have to call it repeatedly if your code is already in the database.
public String getOutputCode() throws SQLException {
String code;
do {
code = new String(RandomCode.generateCode(minLen, maxLen, noOfCAPSAlpha, noOfDigits));
}
while(licenceKeyExists(code));
return code;
}
private boolean licenceKeyExists(String code) throws SQLException {
try{
DB_Connection connect = new DB_Connection();
connection = connect.getDBConnection();
statement = connection.createStatement();
rs = statement.executeQuery("SELECT licenseKey FROM hospital WHERE licenseKey = '" +code+ "'");
return rs.next();
}
finally {
try {
connection.close();
} catch (SQLException ignored){}
}
}
#aween - #captureSteve has answered the first part of the question .
So, straight to "I wan't to call this function" comment. See, if I
understand your question correctly, you want to generate a key, and
check if it is available in the DB using isLicenseKeyExist() . In such
case, why don't you create the key first, then pass it to the
isLicenseKeyExist(). Then this function will return true/false based
on which you can decide what to do.
I have tried to write a code that searches a database of students and shows the searched result on a option pane. And I ended up writing the following. The expected result is:
Name: "something"
Roll: "something"
Registration: "Something"
But actually the output is something like this:
Name: null
Roll: null
Registration: null
public class Search
{
JFrame sw = new JFrame("Search Students' Info"); //search window
JTable stable;
JLabel stfl = new JLabel("Roll"); //search text field label
JTextField stf = new JTextField(8); //search text field
JButton sb = new JButton("Search"); //search button
public void exsearch() //Execute Search
{
sw.setLayout(new GridLayout(2,2));
sw.add(stfl);
sw.add(stf);
sw.add(sb);
sw.setSize(200, 100);
sw.setLocation(100, 100);
sw.setVisible(true);
sb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/srsdb";
try
{
Class.forName(driver).newInstance();
java.sql.Connection con = DriverManager.getConnection(url, "root", "");
JOptionPane.showMessageDialog(null, "Connected", "Connection Confirmation", JOptionPane.PLAIN_MESSAGE);
String str ="SELECT* FROM students WHERE Roll="+stf.getText();
java.sql.Statement st = con.createStatement();
java.sql.ResultSet rs = st.executeQuery(str);
rs.first();
int n = rs.getMetaData().getColumnCount();
// String[] columnnNames;
String[] attributes= new String[10];
int j;
while(rs.next())
{
for(j=0; j<3; j++)
{
attributes[j] = rs.getString(j);
}
}
JOptionPane.showMessageDialog(null, "Name :"+attributes[0]+"\nRoll :"+attributes[1]+"\nRegistration :"+attributes[2], "Search Result", JOptionPane.PLAIN_MESSAGE);
}
catch(Exception f)
{
f.printStackTrace();
JOptionPane.showMessageDialog(null, "Not Found", "Search Result", JOptionPane.PLAIN_MESSAGE);
}
}});
}
public static void main (String[] args)
{
new Search();
}
}
I would use a debugger to check which part of your code is omitted.
One wierd thing I see is, that you jump to the first record in your result set:
rs.first();
And then you read the data from all subsequent records in a while loop
while(rs.next())
{
for(j=0; j<3; j++)
{
attributes[j] = rs.getString(j);
}
}
This ensures, that you get the data from the last matching record if there is more than one.
Better would be to check if there is zero or more than one record. If that is the case, issue a warning because probably there is something wrong with your code (use a debugger to find out what).
If there is only one record, read the data from that record and print it (more or less like you try with rs.getString())
Class.forName ensures that the driver class is on the class path, without needing to compile against the class. It loads the class. No instantiation needed.
A PreparedStatement is better against SQL injection.
Column numbers in the SQL API are 1-based: 1, 2, 3, ... A bit of an exception.
When using first the query loop is as follows. You skipped the first row I think.
Do not forget the miscellaneous close().
Better style to list the columns instead of `*'.
Hence:
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/srsdb";
try
{
Class.forName(driver);
Connection con = DriverManager.getConnection(url, "root", "");
JOptionPane.showMessageDialog(null, "Connected",
"Connection Confirmation", JOptionPane.PLAIN_MESSAGE);
String str ="SELECT Name, Registration FROM students WHERE Roll=?";
PreparedStatement st = con.createPreparedStatement(str);
String roll = stf.getText();
st.setString(1, roll);
String message = "";
java.sql.ResultSet rs = st.executeQuery();
int recno = 0;
if (rs.first()) {
do {
String name = rs.getString(1);
String registration = rs.getString(2);
++recno;
message += "- " + recno + " -\nName: " + name
+ "\nRoll: " + roll
+ "\nRegistration: " + registration + "\n";
} while (rs.next());
}
rs.close();
JOptionPane.showMessageDialog(null, message, "Search Result",
JOptionPane.PLAIN_MESSAGE);
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.