I'm trying to retreive rows from my database and populate a table. I don't understand where the problem is with this code:
if ((report.getMsg()=="selectEventoAll") && (report.getEsito()==1))
{
DefaultTableModel dtm = new DefaultTableModel();
eventi_tb.setModel(dtm);
try
{
ResultSet res_eventi = report.getRes();
i = 0;
Object[][] datiEventi = new Object[report.getRowCount()][5];
while(res_eventi.next())
{
j = 0;
while (j < 5)
{
datiEventi[i][j] = res_eventi.getObject(j+2);
j++;
}
dtm.addRow(datiEventi[i]);
i++;
}
}
This is a bad design. You're mixing your UI and database together. Your code is no good if you change from Swing to a web UI. It's harder to test and debug this way, too.
Break the problem into two pieces: database access and Swing display.
Have one object that does nothing but query for results and load them into a data structure.
Have another that does nothing but accept a data structure and load it into your Swing UI for display.
Your application will have the database decoupled from the user interface. Your testing and debugging life will be easier.
Post more code and perhaps an error message would help us help you faster than guessing.
The loop over the columns in the result set looks suspicious to me. They run from 1 to the number of columns, but you start at 2. Why? If your query has five or fewer columns you'll have an issue there.
Are you sure that your ResultSet contains any rows?
Are you sure that some exception is not occurring before the call to addRow? You're in a try block, what does the catch block do?
Related
Here I have a dilemma.
Let's imagine that we have a sql table like this
enter image description here
It could be a problem when two or more users overwrite data in the table.
How should I check if the place hasn't been taken before update data?
I have two options
in SQL query:
UPDATE ticket SET user_user_id = ? WHERE place = ? AND user_user_id is NULL
or in Service layer:
try {
Ticket ticket = ticketDAO.read(place)
if (ticket.getUser() == null) {
ticket.setUser(user)
ticketDAO.update(ticket)
}else {
throw new DAOException("Place has been already tooken")
}
What way is safer and commonly used in practice?
Please, share your advice.
Possible approach here is to go ahead with SQL query. After query execution check number of rows modified in ticketDAO.update method. If 0 rows modified then throw exception DAOException.
I have an applicaton that executes a query using NamedParameterJdbcTemplate. The resultSet is then parsed row by row using ResultSet.next().
Now in some cases during multi threading scenarios, this goes wrong. The result set is returning wrong values. When I execute the same query in SQLDeveloper, I am seeing the correct values. Not sure what could be the problem behind this.
while (rs.next()) {
count++;
long dbKy = rs.getLong("DBKY");
pAttrs = map.get(dbKy );
if (pAttrs== null) {
pAttrs= new HashMap<String, String>();
map.put(dbKy , pAttrs);
}
log.info( "PrintingResultSet!!::"+rs.getLong("DBKY")
+"::"+rs.getString(ATTR_NAME)
+"::"+rs.getString(ATTR_VAL)
+"::"+rs.getString(Constants.VAL));
pAttrs.put(rs.getString(ATTR_NAME),rs.getString(ATTR_VAL));
}
EDIT: This code is in the repo layer of SpringBoot application. Multithreading is, this issue happens when multiple requests are sent simultaneously. I have printed Thread id in my logs and it confirms that this happens only in multi threaded scenarios.
The value that is being returned actually is the value of some other row.
What values (wrong values) do you see when you are trying to display the resultset. If you see some unknown texts or symbols then probably it could be "encoding" issue. I suggest you to please refer on how to encode values like some special characters/symbols on your service layer since no doubt you will be able to see the data in the database by using the query but if that data contains some special characters/symbols then there is a need of encoding "UTF-8".
Thanks!
I tried to insert a lot of information beside the main task into table as a thread but it appear that it wasn't enough, unfortunately performance is the big issue.
I'm had been using spring and hibernate but still a newbie.
Since I had been using em.persist all the time.
I heard of INSERT ALL from Oracle but it won't go along well with hibernate or maybe it wasn't support since I cannot find any evidence.
Or can you suggest any solution that can help improve the inserting performance, any comment would be appreciated.
This is some code, inside the save() method
List<Obj> listOfObj;
this.save(listOfObj);
public void save(listOfObj){
for (int i = 0; i < listOfObj.size(); ++i)
{
this.em.persist(listOfObj.get(i));
if (i % 1000 == 0)
{
this.em.flush();
this.em.clear();
}
}
java.sql.SQLException: database is locked
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NestedDB.prepare(NestedDB.java:115)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.executeQuery(Stmt.java:89)
When I make a query I get this exception. I read up on it on SA and Google, and the most common conclusion is that someone started making another query which never finished. The problem I'm having is that I've never made a query on this DB on this machine before. I downloaded the db file from where I hosted it (I created it earlier) and haven't done anything with it, so I don't know why it would be locked. When I do a query using a program called SQLite Database Browser, it works just fine. Thanks for the help, I'll provide more info if need be, just let me know.
adapter = new DbAdapter();
ResultSet info;
ResultSet attributes;
for (int i = 1; i < 668; i++) {
if (i%50 == 0) {
System.out.print('.');
}
info = adapter.makeQuery("SELECT * FROM vehicles WHERE id = '" + i + "'");
attributes = adapter.makeQuery("SELECT * FROM vehicle_moves WHERE vehicle_id = '" + i + "'");
if(info.next()) {
base = new (info, attributes);
}
vehicleArray[i] = base;
}
System.out.println("Done.");
info.close();
attributes.close();
adapter.close();
Above is the code where this is occurring. I did some homework throughout my code and sure enough the problem is in this code, other DB queries work just fine. Anything jump out at you guys?
SQLite itself can most certainly handle doing a query while the results of another query are being processed. It'd be terribly useless if that couldn't be done! What's more likely to cause problems is if you've got two connections to the database open at once. I don't know that DbAdapter class at all – not what package it is in, or what module provides it – but if it is assuming that it can open many connections (or if it isn't maintaining proper connection hygiene) then that most certainly would be a cause of the sort of problems you're seeing. Look there first.
Is there an easy or straightforward way in Java to output the results of a DB Query to a file (either csv, tab, etc). Perhaps even in Hibernate?
I know that a query results can be dumped to a flat file on the DB Server. I am looking for a way that an application can run a query and get those results into a file.
I realize one option is to just iterate over the result set and output the records one row at a time separating with a delimiter. But if there is a built in way, or a Hibernate way - that would be much better!
What I am really looking for was a way to do this in code (like - when an application is running). That way a server could take a query, run it against the database, send the output to a flat-file.
The server sending the query doesn't really need the file itself, just to know it worked. So if there is SQL (for an Oracle DB) that could redirect the output to a flat-file in a directory that the Oracle DB Server has access to - that would work too. I don't really have to actually write the file in the Java Server - just trigger the file creation based on the query it has.
Hopefully that makes sense.
You can change the EntityMode of your Session to "DOM4J" so that Hibernate will return the data represented as an XML document instead of a POJO graph.
xmlSession = session.getSession(EntityMode.DOM4J);
Element elem = (Element) xmlSession.load(SomePersistentClass.class, id);
System.out.println(elem.asXML());
You could then easily write this to the file system or do subsequent transformations.
I seem to remember IntelliJ's JDBC db explorer having the ability to export the results of queries. I wouldn't be surprised if an Eclipse or Netbeans DB plugin or can do the same. Here's a whole bunch of open source clients.
There's also JdbcTool, which is a command line client
I realize one option is to just iterate over the result set and output the records one row at a time separating with a delimiter. But if there is a built in way, or a Hibernate way - that would be much better!
No, there is not. But it is very easy:
public void printToFile( ResultSet rs, String path ) throws IOException {
PrintStream out = new FileOutputStream( path );
int cols = rs.getMetaData().getColumnCount();
while( rs.next() ) {
for( int i = 0; i < cols ; i++ ) {
out.printf("%s,", rs.getObject( i ) );
}
out.println();
}
// add exception handling and such...
// or move the from here.
out.close();
rs.close();
}
And then call it like this:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
printToFile( rs, "/some/file" );
This is just from scratch, you'll need to move the closing of the file and rs to something that makes more sense.
So if there is SQL (for an Oracle DB) that could redirect the output to a flat-file in a directory that the Oracle DB Server has access to - that would work too
I think this is possible indeed. But I'm years light away from being a DBA so I don't know "how" to do it.
also change to
for( int i = 1; i < cols ; i++ ) {
out.printf("%s,", rs.getObject( i ) );
}