Object Array duplicate erasing - java

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

Related

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

JTable Repeat Result

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.

Using PreparedStatement to sort records in MySQL

Im trying to write a code in which when a user will click an a "Sort by Name" button, my program will sort the records of my Database and put them in a JTable,combining 2 DB Tables with INNER JOIN. I have managed to do this by using a resultSet and selecting for example Ascending Order. But because I dont want to have 2 buttons, one for the ASC and one for the DESC, I thought of using preparedStatement and an showInputDialog in which the user will select if he wants to have an ASC or a DESC ordering and execute the order. Also, I remembered that some programs I've seen used a feature in which the first time you clicked the button it sorted DESC and if you pressed it again would order by ASC(havent managed to find in on the WEB).About my first thought, I tried to do it but I could get past this one
ResultSetMetaData mdsort = rssort.getMetaData();
I should have an ResultSet variable(rssort) to use getMetaData() but if I selected to make the program with my PreparedStatement i would get an error there. Any suggestions??
try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
Statement stmtsort = conn.createStatement();
ResultSet rssort = stmtsort.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id ORDER BY consoles.name ASC");
// ERROR HERE!!! needs resultset,not preparedStatement
ResultSetMetaData mdsort = rssort.getMetaData();
columnCount = mdsort.getColumnCount();
String[] colssort = new String[columnCount];
for (i=1;i<= columnCount;i++)
{
colssort[i-1] = mdsort.getColumnName(i);
}
DefaultTableModel model = new DefaultTableModel(colssort,0);
while (rssort.next())
{
Object[] rowsort = new Object[columnCount];
for (i = 1 ; i <= columnCount ; i++)
{
rowsort[i-1] = rssort.getObject(i);
}
model.addRow(rowsort);
}
JTable table = new JTable(model);
model.fireTableDataChanged();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(218,59,529,360);
frame.getContentPane().add(table);
model.fireTableDataChanged();
conn.close();
stmtsort.close();
rssort.close();
} catch (SQLException case1)
{case1.printStackTrace();
} catch (Exception case2)
{case2.printStackTrace();}
}
});
UPDATE
OK I managed to fix this issue with the getMetaData() but now the thing is that I dont use any ResultSet variables/instances and cant use next() method to create my DB.
String name = "SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id ORDER BY consoles.name ?";
PreparedStatement psname = conn.prepareStatement(name);
String strin = JOptionPane.showInputDialog(null,"ASC or DESC order ? : ");
psname.setString(1,strin);
psname.executeUpdate();
ResultSetMetaData mdsort = psname.getMetaData();
int columnCount = mdsort.getColumnCount();
.
.
.
// error coming up here,because i deleted the ResultSet
while (psname.next())
.
.
.
Better make a bit more complex TableModel.
That is more optimal.
Keep the data from the ResultSet in an original TableModel.
Use a wrapping TableModel to sort, and maybe filter.
Use the ResultSetMetaData for the column type, if it is Number (Integer, BigDecimal, ...) then use that type instead of Object for the column type: gives a right aligned column.
Maybe first do an internet search for ResultSetTableModel; other peoply must have done it already.
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
String strin = JOptionPane.showInputDialog(null,"ASC or DESC order ? : ");
stmtsortname = conn.createStatement();
rssortname = stmtsortname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id ORDER BY consoles.name "+strin);
mdsortname = rssortname.getMetaData();
columnCount = mdsortname.getColumnCount();
String[] colssortname = new String[columnCount];
for (i=1;i<= columnCount;i++)
{
colssortname[i-1] = mdsortname.getColumnName(i);
}
model = new DefaultTableModel(colssortname,0);
while (rssortname.next())
{
Object[] rowsortname = new Object[columnCount];
for (i = 1 ; i <= columnCount ; i++)
{
rowsortname[i-1] = rssortname.getObject(i);
}
model.addRow(rowsortname);
}
table = new JTable(model);
model.fireTableDataChanged();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true)
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(146,59,763,360);
frame.getContentPane().add(table);
model.fireTableDataChanged();
conn.close();
stmtsortname.close();
rssortname.close();
} catch (SQLException case1)
{
case1.printStackTrace();
}
catch (Exception case2)
{
case2.printStackTrace();
}
}
});

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.

How to get a particular column's values alone?

I am using the mysql java connector. I need java to display the contents of the first column and the second column in different steps. How do I achieve this?
String qry = "select col1,col2 from table1";
Resultset rs = statement.executeQuery(qry);
I've posted a sample below:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
(From: http://www.kitebird.com/articles/jdbc.html#TOC_5 )
Edit: just re-read the question and think you might mean you want to refer to a column later on in code, instead of in the inital loop as in my example above. In that case, you can create an array and refer to the array later on, or, as another answer suggests you can just do another query.
Load them into any data structure of your choice and then display them to your heart's content.
List<String> firstCol = new ArrayList<String>();
List<String> secondCol = new ArrayList<String>();
while(rs.next()){
firstCol.add(rs.getString("col1"));
secondCol.add(rs.getString("col2"));
}
Then you can manipulate with the two list as you want.
How about ... (insert drumroll here):
String qry1 = "select col1 from table1";
Resultset rs1 = statement.executeQuery(qry);
String qry2 = "select col2 from table1";
Resultset rs2 = statement.executeQuery(qry);
(You might want to phrase your question more clearly.)
You can do it like this :
String sql = "select col1,col2 from table1";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) System.out.println(rs.getString("col1"));
I am using following Code:
Statement sta;
ResultSet rs;
try {
sta = con.createStatement();
rs = sta.executeQuery("SELECT * FROM TABLENAME");
while(rs.next())
{
Id = rs.getString("COLUMN_Name1");
Vid = rs.getString("COLUMN_Name2");
System.out.println("\n ID : " + Id);
System.out.println("\n VehicleID: " + Vid);
}
}
catch(Execption e)
{
}
And this code is 100% working.
String emailid=request.getParameter("email");
System.out.println(emailid);
rt=st.executeQuery("SELECT imgname FROM selection WHERE email='emailid'");
System.out.println(rt.getString("imgname"));
while(rt.next())
{
System.out.println(rt.getString("imgname"));
finalimage=rt.getString("imgname");
}

Categories