I wrote a program in java to retrieve images and text data from a table. Everything is right, only when i try to retrieve an image(Blob) from the table, i get an exhausted result set error.I tried google it, but the explanation was fa too condensed. Can anyone help me with this? I will appreciate a nice explanation.
Here is the code
try {
Class.forName(classforname);
Connection con = DriverManager.getConnection(Connectionurl, username, password);
String sql = "Select * from teacherdata where teachername='" + tf1.getText() + "'";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
rs.next();
String thename = rs.getString("teachername");
String sub1, sub2, sub3, sub4;
sub1 = rs.getString("sub1");
sub2 = rs.getString("sub2");
sub3 = rs.getString("sub3");
sub4 = rs.getString("sub4");
String sql2 = "select tid,tpic from teacherimages where teachername='" + tf1.getText() + "'";
PreparedStatement ps2 = con.prepareStatement(sql2);
ResultSet rs2 = ps2.executeQuery(sql2);
rs2.next();
String Tid = rs2.getString("tid");
Blob b = rs.getBlob("tpic");
byte barr
[] = new byte[(int) b.length()]; //an array is created but contains no data
barr = b.getBytes(3, (int) b.length());
Image im = jInternalFrame1.getToolkit().createImage(barr);
ImageIcon icon = new ImageIcon(im);
JLabel label = new JLabel(icon);
Object[] row = {
thename,
sub1,
sub2,
sub3,
sub4,
b,
Tid,
icon
};
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(row);
jTable1.setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(SearchBox.class.getName()).log(Level.SEVERE, null, ex);
}
You are not checking the return value of next on the ResultSet.
Please consider changing your code to
if(result.next()){
// the logic
}
EDIT
Further on the code change , please check that your tables are not empty. If your tables are empty you will not return values.
The error Exhausted Resultset set occurs when you attempt to access the result set after iterating or not checking if the result set returns data
while (resultSet.next()) {
//result set logic
}
//
resultset.getString[1] //<- will throw error Exhausted Resultset
Related
I have some records in my database, which i would like to display on a Jtable in my java application GUI. I have customized the Jtable and added some extra columns which are not in my database.
Kindly assist. The code below only displays a single record in a single column(description column to be specific)
public NewJFrame() {
ArrayList data = new ArrayList();
initComponents();
okay.setVisible(true);
try {
String myDriver = "com.mysql.cj.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/lostfound";
Class.forName(myDriver);
Connection c = DriverManager.getConnection(myUrl, "root", "");
String sql = "SELECT * FROM found";
Statement st = c.createStatement();
// execute the query, and get a java resultset
ResultSet rs =st.executeQuery(sql);
while(rs.next())
{
String name = rs.getString("name");
String description = rs.getString("description");
String location = rs.getString("location");
jTable2.getModel().setValueAt(name, WIDTH, ICONIFIED);
jTable2.getModel().setValueAt(description, WIDTH, ICONIFIED);
jTable2.getModel().setValueAt(location, WIDTH, ICONIFIED);
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
jTable2.show();
}
You are assigning the resultSet data to a single row and column, you need a row counter & increment it for each row, as shown below:
int row=0;
while(rs.next()) {
String name = rs.getString("name");
String description = rs.getString("description");
String location = rs.getString("location");
jTable2.getModel().setValueAt(name, row, 0);//name at column 0 always
jTable2.getModel().setValueAt(description, row, 1);//desc at column 1 always
jTable2.getModel().setValueAt(location, row, 2);//location at column 2 always
row++;//increment row counter for each record
}
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);
}
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.
I am trying to display data from the database into a datatable and I am getting no results. I tested the queries with JDBC with exact select statement to see if it returns any row, and it always worked. But when I try to have the data from the database into my datatable I get no results. I even made a fake dummy data just to populate my datatable. I must be doing something wrong in the index.xhtml file that I don't know of. What could I doing wrong ? any help would be appreciated ?
edit: first I went to with Primefaces with their datatable example, and than I went with simple jsf style datatable like I have here and neither of those worked when I try to do it with the database
UserDAO.java
public class UserDAO {
private static final String USERNAME = "something";
private static final String PASSWORD = "something";
private static final String CONN_STRING =
"jdbc:sqlserver://petunia.arvixe.com.....something";
public List<Report> getUserList() {
List<Report> list = new ArrayList<Report>();
PreparedStatement ps = null;
Connection con = null;
ResultSet result = null;
try {
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
while (result.next()) {
Report rep = new Report();
rep.setId(result.getInt("id"));
rep.setTag(result.getString("tag"));
rep.setName(result.getString("asset_name"));
rep.setModel(result.getString("model"));
rep.setSerial(result.getString("ser_no"));
rep.setValue(result.getFloat("value"));
rep.setCondition(result.getString("asset_condition"));
rep.setType(result.getString("asset_type"));
rep.setLocationName(result.getString("name"));
rep.setAddress(result.getString("address"));
rep.setCity(result.getString("city"));
rep.setState(result.getString("state"));
rep.setZip(result.getString("zip"));
rep.setPhone(result.getString("phone"));
rep.setDistrict(result.getInt("district"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
}
Well, you are making a report:
Report rep = new Report();
...but not adding it to your list. Add this:
Report rep = new Report();
list.add(rep);
I suppose your problem is this code:
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You are overwriting your sql statement immediately with the statement sql1.
I think, you probably want to select the assets with THEIR locations. In SQL you can use a JOIN to achieve that.
If you use this syntax
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You will get as a result only the execution of the second query. I think that in your case you are trying to get a result from both tables assets and location so you should use a join between the 2 tables.
Im working with Java EE and derby, i try to get data from my resultset and put them in int and string but don't work it gives me this error :
java.sql.SQLException: Invalid operation for the current cursor location.
i tryed result.next() but nothing, here is my code :
Connection conn = null;
Statement stmt = null;
ResultSet result = null;
Hotel hot = new Hotel();
try {
synchronized (dataSource) {
conn = dataSource.getConnection();
}
stmt = conn.createStatement();
String req = "SELECT * FROM hotel WHERE num = " + num;
result = stmt.executeQuery(req);
}
//result.next();
int xxnum = result.getInt(1);
String nom = result.getString("nom");
String villeV = result.getString("ville");
int etoilesV = result.getInt("etoiles");
String directeur = result.getString("directeur");
Hotel hol = new Hotel(num, nom, villeV, etoilesV, directeur);
result.close();
stmt.close();
return hol;
} catch (SQLException ex) {
throw new DAOException("probl�me r�cup�ration de la liste des hotels !!", ex);
} finally {
closeConnection(conn);
}
The error
java.sql.SQLException: Invalid operation for the current cursor location.
will be caused by not setting the cursor to the next position using
result.next();
Place the call in an if statement
if (result.next()) {
// build Hotel object
...
}
If you still don't see any results, run your SQL directly against your database and see if any records are returned. If not, adjust your query or data accordingly.
Side Notes:
Use PreparedStatement to protect against SQL Injection attacks.
Place result.close(); and stmt.close(); calls in a finally block.
You need to use next() method of ResultSet.
Check the Javadocs here and I have snipped the relevant part below.
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
So you need to do this in your code:
if(result.next())
{
int xxnum = result.getInt(1);
String nom = result.getString("nom");
String villeV = result.getString("ville");
int etoilesV = result.getInt("etoiles");
String directeur = result.getString("directeur");
}