JTable Repeat Result - java

My problem is that I have a JTable that always prints the first line repeatedly, and ignores the following data. I think that is the problem code.
I do a query and converts it to a list to populate my JTable. I ask you to analyze my code to see if it is right.
try{
EntityManager em = EntityManagerUtil.getEntityManager();
em.getTransaction().begin();
Query query_resultados = em.createQuery("FROM "
+ "Resultados WHERE res_codigo LIKE "+aux);
List<Resultados> lista_resultados =
(List<Resultados>) query_resultados.getResultList();
for(int i=0; i<lista_resultados.size(); i++){
Resultados resultado = lista_resultados.get(i);
System.out.println("Teste: "+lista_resultados.get(i).getRes_anti_hbc_hbs());
System.out.println("i= "+i);
model.addRow(new Object[] {resultado.getRes_anti_hbc_hbs(),
resultado.getRes_anticorpos_irregulares(),
resultado.getRes_chagas(), resultado.getRes_codigo(),
resultado.getRes_data(), resultado.getRes_ggpd(),
resultado.getRes_hbs_aq(), resultado.getRes_hcv(),
resultado.getRes_hiv(), resultado.getRes_htlv_i_ii(),
resultado.getRes_malaria(), resultado.getRes_responsavel(),
resultado.getRes_sifilis(), resultado.getRes_t_mancha(),
resultado.getRes_tpg()});
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro: "+e);
}

In Java it is common to iterate over a Java ResultSet by using something like this:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String firstColVal = rs.getString(1);
}
rs.next() ensures in this context that the next lines is fetched until all lines are done.

Related

Problem with diacritic, getting data from database java

I have MySQL database, where I have saved data and some words have diacritics.
This is my function how to get data from database.
public List<RowType> getData(String query){
List<RowType> list = new ArrayList<>();
try{
connect();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()){
StringBuilder str = new StringBuilder();
for(int i = 1; i <= getCountColumns(resultSet); i++){
if(i==1) str.append(resultSet.getString(i));
else str.append("," + resultSet.getString(i));
}
list.add(new RowType(str.toString()));
}
}
catch(Exception e){
System.out.println("Chyba při získavání údajů z databáze.");
System.out.println(e);
Console.print("Chyba při získavání údajů z databáze.");
Console.print(e.toString());
}
finally{
disconnect();
}
return list;
}
As parameter i send this query.
List<RowType> list = connection.getData("Select id from countries where name = 'Česko'");
But it doesn´t find anything, because i have diacritic in the query ("Česko"). I try it without diacritic and it works. So don´t you know how to fix it to work with accents too?
Can you try to add a few more queries before executing your main query?
so it will look something like:
connect();
Statement statement = connection.createStatement();
String query2 = "SET NAMES 'utf8'";
statement.execute(query2);
query2 = "SET CHARACTER SET 'utf8'";
statement.execute(query2);
ResultSet resultSet = statement.executeQuery(query);
if the above does not work for you, then maybe there is an issue with your database settings; if that's the case, you can refer to the answer here

Java: SQL Query: rs.next() is false after updating a column

I have a strange problem. I have a database and I want to change the values of a column. The values are safed in an Arraylist (timelist).
In order to write the values in the right row, I have a second Arrylist (namelist). So I want to read the first row in my Database, than I check the namelist and find the name. Than i take the matching value out of the timelist and write it into the database into the column "follows_date" in the row, matching to the name.
And than I read the next row of the Database, until there are no more entries.
So the strange thing is, if I change nothing in the database, the while(rs.next()) part works.
For example:
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //liest die namen
}
}
This would print me every name after name. But when I change the table, the while loop ends after that. (no error, the program just finishes)
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //writes the name
//look, if name is in Arraylist "namelist"). if yes, than write the matching date from "timelist" into the database.
if (namelist.contains(name)){
System.out.println("name found: "+ name);
int listIndizi = namelist.indexOf(name); //get index
Long indiziDatum = (long) timelist.get(listIndizi); //get date from same Index
System.out.println(indiziDatum); // print date so i can see it is correct (which it is)
statement.executeUpdate("UPDATE users SET follows_date ="+ indiziDatum +" WHERE username = '"+name+"'"); //updates the follows_date column
}
}
Everything works fine, except that now, the while loop doesn't continues after the first passage, but ends.
The resultSet of a statement is closed and will not return further results if you execute another statement. Create a new separate statement object for the update and everything should work as excepted.
Statement statement1 = connection.createStatement();
Statement statement2 = connection.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SELECT username FROM users");
while(resultSet1.next()){
...
statement2.executeUpdate("UPDATE users ..."));
}
As to Why it happens:
Here is the explanation from the official documentation:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
Alternative Approach:
From your sample, it seems you are trying to update the "same" row in your resultSet, you should consider using an Updatable ResultSet.
Sample code from the official documentation:
public void modifyPrices(float percentage) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT * FROM " + dbName + ".COFFEES");
while (uprs.next()) {
float f = uprs.getFloat("PRICE");
uprs.updateFloat( "PRICE", f * percentage);
uprs.updateRow();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}

Object Array duplicate erasing

I need to erase duplicates in Object example[]
And Object example is filled like this:
final Object example[] = new Object[rowCount];
try{
int row = 0;
Statement st = conn.createStatement();
rs = st.executeQuery("SELECT * FROM Table1");
while(rs.next()){
example[row] = rs.getString("Name");
row++;
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "DBComboBoxFill error: " + e);
}
And i need it for:
JComboBox combobox = new JComboBox(example)
I know how to do that whit Integers, 1st sort them, then check whit if statement and erase. I don't know, maybe i can do it whit ArrayList, but will the ComboBox get values from ArrayList?
If the only column you want is Name (which is what it looks like from the code) then you can instead retrieve just that column in the query, and then you can use DISTINCT to avoid duplicates (as suggested by SubOptimal).
That is, change the query from SELECT * FROM Table1 to SELECT DISTINCT Name FROM Table1 as shown below.
final Object example[] = new Object[rowCount];
try{
int row = 0;
Statement st = conn.createStatement();
rs = st.executeQuery("SELECT DISTINCT Name FROM Table1");
while(rs.next()){
example[row] = rs.getString("Name");
row++;
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "DBComboBoxFill error: " + e);
}

Formatting in a textArea append. Java

how do you format text in a textArea when appending it?
try{
//establish connection to database
connection= DriverManager.getConnection(DATABASE_URL, "Hotel", "1234");
//create statement for querying database
statement = connection.createStatement();
// statement.executeUpdate("INSERT INTO TBLSTUDENT VALUES("+id+",'"+name+"','"+course+"',"+age+")");
//query database
resultSet = statement.executeQuery("SELECT * FROM Customer");
//process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
textArea.append("Hotel Database: \n");
for(int i=1; i<=numberOfColumns; i++){
textArea.append(metaData.getColumnName(i));//"%-8s\t",
}
System.out.println();
while(resultSet.next()){
for(int i=1; i<=numberOfColumns;i++){
textArea.append(resultSet.getObject(i).toString());
}
System.out.println();
}
}catch(SQLException sqlException){
sqlException.printStackTrace();
}
Right now the output is that it only appends into one line.
And it should be
Column 1-Column 2-Column 3
data1-data 2-data 3
I tried using the formatting %-8s\t but it doesn't work on .append()
Generally speaking, JTextArea's not the best choice, you should be using a JTable
See How to Use Tables for more details
However, try using something more like textArea.append(String.format("%-8s\t", metaData.getColumnName(i))); instead
You will also need to append a new line character (\n) between the lines

Getting next value from sequence

I have a bit of code here to get the next value of my sequence, but it is adding the total number of records onto the result each time.
I'm only learning about prepared Statements, I'm thinking this is something small, maybe rset.next() should be something else?
public void add( String title, String actor, String genre ) {
try {
String sql2 = "Select movie_seq.nextval from Movie";
pstmt = conn.prepareStatement(sql2);
rset = pstmt.executeQuery();
int nextVal = 0;
if(rset.next())
nextVal = rset.getInt(1);
String queryString = "Select MovieID, Title, Actor, Genre from Movie";
pstmt = conn
.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rset = pstmt.executeQuery();
rset.moveToInsertRow();
rset.updateInt(1, nextVal);
rset.updateString(2, title);
rset.updateString(3, actor);
rset.updateString(4, genre);
rset.insertRow();
pstmt.executeUpdate();
} catch (SQLException e2) {
System.out.println("Error going to previous row");
System.exit(1);
}
}
Any help appreciated.
I think you don't need the call to pstmt.executeUpdate();
As stated in ResultSet doc, the function insertRow stores the row in the Dataset AND in the database.
The following code shows all that's necessary to add a new row:
rset.moveToInsertRow(); // moves cursor to the insert row
rset.updateString(1, "AINSWORTH"); // updates the
// first column of the insert row to be AINSWORTH
rset.updateInt(2,35); // updates the second column to be 35
rset.updateBoolean(3, true); // updates the third column to true
rset.insertRow();
rset.moveToCurrentRow();
Why dont you iterate using while rather than if . something like this
List lst = new ArrayList();
Someclass sc = new SomeClass(); //object of the class
String query = "SELECT * from SomeTable";
PreparedStatement pstmt = sqlConn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
Role role = null;
while (rs.next()) {
String one = rs.getString(1);
String two = rs.getString(2);
boolean three = rs.getBoolean(3);
//if you have setters getters for them
sc.setOne(one);
sc.setTwo(two);
sc,setThree(three);
lst.add(sc)
}
//in the end return lst which is of type List<SomeClass>
}
Shouldn't you be doing this instead?:
String sql2 = "Select " + movie_seq.nextval + " from Movie";
As it is, it seems like you're passing a slightly bogus string into the SQL query, which is probably defaulting to the max index (not 100% positive on that). Then rs.next() is just incrementing that.

Categories