remove last word continuously and check in database table java - java

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();
}

Related

Convert a ResultSet to a String

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

Resultset always empty when doing executeQuery

I am currently writing a simple Java app that reads information from an XLS file and then enters it in the database. Since that XLS does have duplicated records, I do a simple check if the entry in the XLS file already exists in the database. Here is my code:
public static void addResult(ArrayList<ArrayList<String>> listResults)
{
try
{
openDatabase();
stmt = c.createStatement();
for (int i = 0; i < listResults.size(); i++)
{
PreparedStatement stm = c.prepareStatement("SELECT player_name FROM results WHERE player_name=?;");
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
System.out.println(stm);
ResultSet rs = stm.executeQuery();
if (rs.getRow() <= 0)
{
String typeOfPlay = new String();
if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Simple"))
{
typeOfPlay = "single";
}
else if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Double"))
{
typeOfPlay = "double";
}
stm = c.prepareStatement("INSERT INTO results (player_name, school_id, " + typeOfPlay + ", tournament_id) "
+ "VALUES(?,?,?,?);");
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
stm.setString(2, listResults.get(i).get(ReadResultsFile.SCHOOL_ID));
stm.setInt(3, Integer.parseInt(listResults.get(i).get(ReadResultsFile.SCORE)));
stm.setString(4, "1");
stm.executeUpdate();
}
else
{
String typeOfPlay = new String();
if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Simple"))
{
typeOfPlay = "single";
}
else if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Double"))
{
typeOfPlay = "double";
}
stm = c.prepareStatement("UPDATE results SET " + typeOfPlay + "=? WHERE player_name=?;");
stm.setString(1, typeOfPlay);
stm.setString(2, listResults.get(i).get(ReadResultsFile.SCORE));
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
System.out.println(stm);
stm.executeUpdate();
}
}
closeDatabase();
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
The problem that arises is that the rs.getRow() function always returns -1. I tried running the SELECT query directly in the database tool and the query returns the player_name column if there is already a similar entry existing. It unfortunately do the same in Java.
I am unsure what to do at this point.
Thank you for any hint!
getRow will not work as per the javadocs
Retrieves the current row number. The first row is number 1, the second number 2, and so on.
and
A ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row
Usually use
while (rs.next ()) {....

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException UNKNOWN COLUMN

I am currently trying to scan and parse the file that is not in sql format. I am trying to input all the data into the SQL table but for some reason every time i run the program, i get the error saying unknown column 'what' in 'field list.' So the neither of the data goes through. 'what' is one of the names that is on the text. The table currently has 11 columns. I know I am parsing or scanning it wrong but I cannot figure out where. Here is my code:
public class parseTable {
public parseTable (String name) throws FileNotFoundException
{
File file = new File(name);
parse(file);
}
private void parse(File file) throws FileNotFoundException
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/";
String connectionUser = "";
String connectionPassword = "";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
String query = "";
for(int i = 0; i < rowInfo.length; i++)
{
if(query.equals(""))
{
query = rowInfo[i];
}
else if(i == 9){
query = query + "," + rowInfo[i];
}
else if(rowInfo[i].equals(null)){
query = query + ", " + "NULL";
}
else
query = query + ", " + "'" + rowInfo[i] + "'";
}
stmt.executeUpdate("INSERT INTO dup VALUES(" + query + ")");
count = 0;
rowInfo = new String[11];
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
And this is the data I'm trying to input:
1 hello cheese 1111 what#yahoo.com user adm street zip what USA
2 Alex cheese 1111 what#yahoo.com user adm street zip what USA
So this is my new code now, using PrepareStatement. However I still get an error and I looked online for the solution on where I'm making a mistake, but I cant seem to figure out where.
String query = "INSERT INTO mil_table (UserName, NameFirst, NameLast, supportID, EmailAddress, Password,
IDQ, AddressCity, AddressState, AddressZip, AddressCountry) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(query);
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
for(int i = 0; i <rowInfo.length; i++)
{
pstmt.setString(i + 1, rowInfo[i]);
}
//stmt.executeUpdate("INSERT INTO mil_table VALUES(" + query + ")");
//System.out.println("#" + query + "#");
pstmt.executeUpdate();
count = 0;
rowInfo = new String[11];
}
}
As you are using MySQL, you will need to enclose the text inputs with quotes. Try enclosing the String values that you are inserting in quotes and then execute your code.

How to show a arraylist of string on jlabel?

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.

How I can return query result from Server to Client

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.

Categories

Resources