Scroll sensitive resultset
hi,
I'm developing client/server appliaction,back end is MS sql 2000 db.
I need to display 100,000+ records in JTable.
I created Statement object with SCROLL_SENSITIVE and i read 40 records
from opened resultset.Note I close the resultset when the user closes JTable.
Now my problem is
How to make others inserts visible in jtable?
Does it depends on Driver implementation?
How do u guys implemented?
thanx
mohan
Heh, it depends from the order in which you displaying records from the table or view. If you simply order your result set by ID then you could display them in the decsending order, so the last one comes as the first one in the result set. If your record fall on the middle of the result set then you should find it in the result set to get an index in the table. Then simply put selection on it. Also make sure the new record is prefetched via the underlying database before you searching the table.
Does it make sense?
Similar Messages
-
Scroll Sensitive ResultSet problem
Hi,
This is viquar.
Iam using Type4 driver for oracle8i i.e oralce.jdbc.driver.OracleDriver
and creating a scroll sensitive resultset using
Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
and iam calling the method refereshRow();
But it gives me an error :Unsupported Feature refreshRow.
When I checked out in detail..I came to know that the Type of ResultSet getting created is SCROLL INSENSITIVE(value 1004) instead of SCROLL SENSITIVE(value 1005).
Please help me in this.hi,
to know whether your database supports result sets run this test:
try {
DatabaseMetaData dmd = connection.getMetaData();
if (dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)) {
// Insensitive scrollable result sets are supported
if (dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)) {
// Sensitive scrollable result sets are supported
if (!dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)
&& !dmd.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE)) {
// Updatable result sets are not supported
} catch (SQLException e) {
}and to know whether a result set is scrollable, run this test:
try {
// Get type of the result set
int type = resultSet.getType();
if (type == ResultSet.TYPE_SCROLL_INSENSITIVE
|| type == ResultSet.TYPE_SCROLL_SENSITIVE) {
// Result set is scrollable
} else {
// Result set is not scrollable
} catch (SQLException e) {
}BTW, did you try ojdbc.14 driver ?
hth -
SCROLL SENSITIVE vs SCROLL INSENSITIVE
Hi,
I'm trying to understand the difference between these two - I wrote a small piece of code that I thought would explain the difference. However, when I run this code (By toggling the scroll sensitivity between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE),
I don't see any change in the output. Essentially - I'm trying to run through a resultset WHILE SIMULTAENOUSLY changing the underlying data. I assumed the insensitive scroll type wouldn't detect this change while the sensitive type would!! But BOTH don't detect the change.
I even tried the same scenario by creating a different connection in the thread just to eliminate the fact that the same connection being used in the thread was probably the culprit - didnt help either. I'm no closer to understanding the difference between the two Scroll types now :( Please help!!! The result is in the end - even though the update went through - the SCROLLABLE SENSITIVE resultset didn't pick it up!!!
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.naming.*;
public class JDBCTest {
public static void main(String argv[]) throws Throwable {
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(driverName);
String connectionURL = "jdbc:sqlserver://localhost:1433;databaseName=FXTraderDB;userName=sa;password=Marcos!23";
Connection conn = DriverManager.getConnection(connectionURL);
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
TableUpdater updater = new TableUpdater(conn);
updater.start();
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("Select * from hs_market_data");
rs.afterLast();
while(rs.previous()) {
int id = rs.getInt("id");
int insaddr = rs.getInt("insaddr");
double bidRate = rs.getDouble("bidRate");
double askRate = rs.getDouble("askRate");
System.out.println(String.format("Id : %d. Insaddr : %d bidRate : %f askRate : %f", id, insaddr, bidRate, askRate));
Thread.sleep(2000);
rs.close();
stmt.close();
class TableUpdater extends Thread {
private Connection conn = null;
public TableUpdater(Connection conn) {
this.conn = conn;
public void run() {
try {
System.out.println("UPDATING AFTER WAITING FOR 5 SECONDS!!...");
Thread.sleep(5000);
Statement stmt = conn.createStatement();
double bidRate = new Random().nextDouble()*100;
double askRate = new Random().nextDouble()*150;
System.out.println(String.format("### Updating the rows (55, 50, 45, 40, 35) with bidRate : %f askRate : %f ###" ,bidRate, askRate));
stmt.executeUpdate(String.format("update hs_market_data set bidRate=%f, askRate=%f where id in (55, 50, 45, 40, 35)", bidRate, askRate));
stmt.close();
} catch(Throwable t) {
t.printStackTrace();
UPDATING AFTER WAITING FOR 5 SECONDS!!...
Id : 58. Insaddr : 5 bidRate : 69.500000 askRate : 70.500000
Id : 57. Insaddr : 4 bidRate : 68.500000 askRate : 69.500000
Id : 56. Insaddr : 4 bidRate : 67.500000 askRate : 68.500000
*### Updating the rows (55, 50, 45, 40, 35) with bidRate : 81.512883 askRate : 2.874984 ###*
Id : 55. Insaddr : 1 bidRate : 555.220000 askRate : 333.330000
Id : 54. Insaddr : 6 bidRate : 65.500000 askRate : 66.500000
Id : 53. Insaddr : 5 bidRate : 64.500000 askRate : 65.500000
Id : 52. Insaddr : 6 bidRate : 63.500000 askRate : 64.500000
Id : 51. Insaddr : 2 bidRate : 62.500000 askRate : 63.500000
Id : 50. Insaddr : 7 bidRate : 555.220000 askRate : 333.330000
Id : 49. Insaddr : 1 bidRate : 60.500000 askRate : 61.500000There are no guarantees that this flag will be honoured so it would be unwise to rely upon any specific behaviour.
-
Problem with Sensitive ResultSet in SQL Server 2000
Hi,
I am trying to use SCROLL_SENSITIVE and CONCUR_UPDATABLE ResultSet accessing SQL Server 2000. I am using JDK 1.3 and supported JDBC driver. When I tried to insert a row, I got the following message:
sp_cursor: The cursor identifier value provided (0) is not valid
Is there any setting in SQL Server that I need to configure or do I miss something in my code?
Thanks,
Andi Setiyadi
Here are my codes:
cs = connection.prepareCall("{call sp_deptInfo (?,?,?)}", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
cs.setInt(1, 0);
cs.setString(2, "");
cs.setString(3, "name/orderbyid");
rs = cs.executeQuery();
rs.last();
int rows = rs.getRow();
rs.afterLast();
rs.moveToInsertRow();
rs.updateInt(1, rows + 1);
rs.updateInt(2, Integer.parseInt(parentDept));
rs.updateString(3, newDept);
rs.updateInt(4, 1);
rs.insertRow();I am getting the resultset by calling a stored procedure. I am not changing the stored procedure itself.Database drivers create 'connections' and 'statements' which match the SQL that you pass it. You are passing it a stored proc. The only information that it has is on a stored proc. It doesn't matter where the stored proc got its info from. The stored proc doesn't return tables and indexes into tables. It returns a result set (that is what your code suggests.) That is all the information that the driver has.
Consider your stored proc might return this
select * from mytable where ....
But it could also do this
select 'value1', 'value2', ... from dual
On the java side it isn't not going to know which of the above that you did. Nor should it. And you can't update/insert into that second example.
Or at least that is how I look at it.
Your code looks like it is trying to 'update' the result set that a stored proc returned. And I simply don't see how that is possible. Or even why anyone would want to do it. -
How can a user scroll the resultset obtained from a servlet in a jsp page?
Actually i am having a page where user has to select company name and for tht i am providing him with a button, and on clicking tht button a
new search page is provided , and on mentioning the search criteria ,a servlet is fired which returns a list of companies(tbasically i am creating a session object of resultset type which stores the companies name), now the servlets again goes back to search page, and here i want 2 display the company names, i am able to display company names in my search page , but now i want my user to select one of the companies from tht servlet.
for tht i need to tap the onMouseOver function of java SCript, C
Can any one tell me how to write code for tht
Thanking in Advancesee https://addons.mozilla.org/en-US/thunderbird/addon/send-later-3/
-
Multiple users, avoiding data loss
Hi, Here is the problem
User a reads data from row r in table t
User b reads data from row r in table t
User b updates data and writes back to table t
User a updates data and writes back to table t
User b's update was lost.
We are using custom DAO, JDBC, a transaction level of Read_Committed, a connection pool, Oracle DB and OC4J
I think that the DB would be fine as far as consistency is concerned, but What I'd like to know is the best way to stop user b's update being lost as they would think they had made an update but the DB wouldn't reflect this?
Any help/ideas greatly appreciatedCheers for responding Avi,
Okay so I need to code it rather than rely on the Database, what is the best way to go?
In my opinion, the real problem is showing user "a"
the row with user "b"'s update. Would a
scroll-sensitive "ResultSet" ensure that? (I don't
know, since I haven't tried it.)This won't be a problem as users a&b are at the same level and can change the same rows.
But once user "a" has overwritten user "b"'s change,
then user "b"'s change is gone. What would you
expect? A message to user "a" saying, 'sorry, you
can't change this row because another user already
has!'Something like that I was thinking of just putting up the jsp again causing the DAO to re-read the record, with a message telling the user what has happened. For this app we can't have customer info (possibly entered by user b) disappear...
Any further ideas? or places to go look? -
Everything is scroll insensitive
I'm using this code:
public Vector executeSQL(String sql, Integer resultSetType,
Integer resultSetConcurrency) throws SQLException
if(conn == null)requestConnection();
if(resultSetType == null)
resultSetType = new Integer(ResultSet.TYPE_FORWARD_ONLY);
if(resultSetConcurrency == null)
resultSetConcurrency = new Integer(ResultSet.CONCUR_READ_ONLY);
Vector results = new Vector();
java.sql.Statement stmt = conn.createStatement(resultSetType.intValue(),
resultSetConcurrency.intValue());
if(stmt.execute(sql))
rs = stmt.getResultSet();
No matter what I pass in for the scroll type, it comes back as scroll insensitive. I'm using Oracle 8.1.7 with the jdbc-odbc bridge. I would suspect that scroll sensitive might not be supported, but I can't set it to forward only either.
Anyone seen this one before?Hi,
Scrollable resultsets depend on the driver ur using and not on the select statement as u have mentioned in your post.
Use jsqlconnect driver to use scrollable resultset.
Seetesh -
Need help with inserting rows in ResultSet and JTable
hello Guru!
i have inserted a row in my result set and i want that my table shows this row promptly after i have inserted it in my result set...
but when i use following code for my resultset:
rs.moveToInsertRow();
rs.updateInt(1,nr);
rs.updateString(2, name);
rs.insertRow();
Record are inserted in resultset and database but not shown in my JTable??
Anyone a Clue to without reexecuting the query how can i display inserted row in JTable
http://download-west.oracle.com/docs/cd/A87860_01/doc/java.817/a83724/resltse7.h
I have refrered the following links but still clue less help Guruuuuuuu
i m really in trobble??????i am just near by the Solution using the Database Metadata
by couldn't get the ideaaaa
==================================================
http://download-west.oracle.com/docs/cd/A87860_01/doc/java.817/a83724/resltse7.htm
Seeing Database Changes Made Internally and Externally
This section discusses the ability of a result set to see the following:
its own changes (DELETE, UPDATE, or INSERT operations within the result set), referred to as internal changes
changes made from elsewhere (either from your own transaction outside the result set, or from other committed transactions), referred to as external changes
Near the end of the section is a summary table.
Note:
External changes are referred to as "other's changes" in the Sun Microsystems JDBC 2.0 specification.
Seeing Internal Changes
The ability of an updatable result set to see its own changes depends on both the result set type and the kind of change (UPDATE, DELETE, or INSERT). This is discussed at various points throughout the "Updating Result Sets" section beginning on , and is summarized as follows:
Internal DELETE operations are visible for scrollable result sets (scroll-sensitive or scroll-insensitive), but are not visible for forward-only result sets.
After you delete a row in a scrollable result set, the preceding row becomes the new current row, and subsequent row numbers are updated accordingly.
Internal UPDATE operations are always visible, regardless of the result set type (forward-only, scroll-sensitive, or scroll-insensitive).
Internal INSERT operations are never visible, regardless of the result set type (neither forward-only, scroll-sensitive, nor scroll-insensitive).
An internal change being "visible" essentially means that a subsequent getXXX() call will see the data changed by a preceding updateXXX() call on the same data item.
JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
boolean ownDeletesAreVisible(int) throws SQLException
boolean ownUpdatesAreVisible(int) throws SQLException
boolean ownInsertsAreVisible(int) throws SQLException
Note:
When you make an internal change that causes a trigger to execute, the trigger changes are effectively external changes. However, if the trigger affects data in the row you are updating, you will see those changes for any scrollable/updatable result set, because an implicit row refetch occurs after the update.
Seeing External Changes
Only a scroll-sensitive result set can see external changes to the underlying database, and it can only see the changes from external UPDATE operations. Changes from external DELETE or INSERT operations are never visible.
Note:
Any discussion of seeing changes from outside the enclosing transaction presumes the transaction itself has an isolation level setting that allows the changes to be visible.
For implementation details of scroll-sensitive result sets, including exactly how and how soon external updates become visible, see "Oracle Implementation of Scroll-Sensitive Result Sets".
JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
boolean othersDeletesAreVisible(int) throws SQLException
boolean othersUpdatesAreVisible(int) throws SQLException
boolean othersInsertsAreVisible(int) throws SQLException
Note:
Explicit use of the refreshRow() method, described in "Refetching Rows", is distinct from this discussion of visibility. For example, even though external updates are "invisible" to a scroll-insensitive result set, you can explicitly refetch rows in a scroll-insensitive/updatable result set and retrieve external changes that have been made. "Visibility" refers only to the fact that the scroll-insensitive/updatable result set would not see such changes automatically and implicitly.
Visibility versus Detection of External Changes
Regarding changes made to the underlying database by external sources, there are two similar but distinct concepts with respect to visibility of the changes from your local result set:
visibility of changes
detection of changes
A change being "visible" means that when you look at a row in the result set, you can see new data values from changes made by external sources to the corresponding row in the database.
A change being "detected", however, means that the result set is aware that this is a new value since the result set was first populated.
With Oracle8i release 8.1.6 and higher, even when an Oracle result set sees new data (as with an external UPDATE in a scroll-sensitive result set), it has no awareness that this data has changed since the result set was populated. Such changes are not "detected".
JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
boolean deletesAreDetected(int) throws SQLException
boolean updatesAreDetected(int) throws SQLException
boolean insertsAreDetected(int) throws SQLException
It follows, then, that result set methods specified by JDBC 2.0 to detect changes--rowDeleted(), rowUpdated(), and rowInserted()--will always return false with the 8.1.6 Oracle JDBC drivers. There is no use in calling them.
Summary of Visibility of Internal and External Changes
Table 12-1 summarizes the discussion in the preceding sections regarding whether a result set object in the Oracle JDBC implementation can see changes made internally through the result set itself, and changes made externally to the underlying database from elsewhere in your transaction or from other committed transactions.
Table 12-1 Visibility of Internal and External Changes for Oracle JDBC
Result Set Type Can See Internal DELETE? Can See Internal UPDATE? Can See Internal INSERT? Can See External DELETE? Can See External UPDATE? Can See External INSERT?
forward-only
no
yes
no
no
no
no
scroll-sensitive
yes
yes
no
no
yes
no
scroll-insensitive
yes
yes
no
no
no
no
For implementation details of scroll-sensitive result sets, including exactly how and how soon external updates become visible, see "Oracle Implementation of Scroll-Sensitive Result Sets".
Notes:
Remember that explicit use of the refreshRow() method, described in "Refetching Rows", is distinct from the concept of "visibility" of external changes. This is discussed in "Seeing External Changes".
Remember that even when external changes are "visible", as with UPDATE operations underlying a scroll-sensitive result set, they are not "detected". The result set rowDeleted(), rowUpdated(), and rowInserted() methods always return false. This is further discussed in "Visibility versus Detection of External Changes".
Oracle Implementation of Scroll-Sensitive Result Sets
The Oracle implementation of scroll-sensitive result sets involves the concept of a window, with a window size that is based on the fetch size. The window size affects how often rows are updated in the result set.
Once you establish a current row by moving to a specified row (as described in "Positioning in a Scrollable Result Set"), the window consists of the N rows in the result set starting with that row, where N is the fetch size being used by the result set (see "Fetch Size"). Note that there is no current row, and therefore no window, when a result set is first created. The default position is before the first row, which is not a valid current row.
As you move from row to row, the window remains unchanged as long as the current row stays within that window. However, once you move to a new current row outside the window, you redefine the window to be the N rows starting with the new current row.
Whenever the window is redefined, the N rows in the database corresponding to the rows in the new window are automatically refetched through an implicit call to the refreshRow() method (described in "Refetching Rows"), thereby updating the data throughout the new window.
So external updates are not instantaneously visible in a scroll-sensitive result set; they are only visible after the automatic refetches just described.
For a sample application that demonstrates the functionality of a scroll-sensitive result set, see "Scroll-Sensitive Result Set--ResultSet5.java".
Note:
Because this kind of refetching is not a highly efficient or optimized methodology, there are significant performance concerns. Consider carefully before using scroll-sensitive result sets as currently implemented. There is also a significant tradeoff between sensitivity and performance. The most sensitive result set is one with a fetch size of 1, which would result in the new current row being refetched every time you move between rows. However, this would have a significant impact on the performance of your application.
how can i implement this using
JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
boolean deletesAreDetected(int) throws SQLException
boolean updatesAreDetected(int) throws SQLException
boolean insertsAreDetected(int) throws SQLException -
Trying to get the last row from a resultset
Hi,
I'm trying to do a query to postgreSQL and have it return the last updated value, (last row).
My prepared statement is returning the correct results, but i'm having a problem getting the latest value.
I'm using a comboBox to drive a textfield, to load the last entered values in depending on which item in the comboBox is selected.
I've tried a variety of things and most seem to return the first row, not showing the updated values.
Or, if it does work, it takes to long to load, and i get an error.
here is the working code;
Object m = machCBX.getSelectedItem():
try { PreparedStatment last = conn.prepareStatement("SELECT part, count FROM production WHERE machine = ?",
ResultSet.TYPE_SCROLL_INSENSITIVE, //tried both INSENSITIVE and SENSITIVE
ResultSet.CONCUR_READ_ONLY);
last.setString(1, String.valueOf(m));
rs. = last.executeQuery();
if(rs.isAfterLast) == false ) {
rs.afterLast();
while(rs.previous()) {
String p = rs.getString("part");
int c = rs.getInt("count");
partJTX.setText(p);
countJTX.setText(c);
}this grabs values, but they are not the last entered values.
Now if i try to use rs.last() it returns the value i'm looking for but takes to long, and i get:
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space I also know using ra.last() isn't the best way to go.
I'm just wondering if there is another way other than getting into vectors and row count? or am i better off to go with the later?
thanks
-PDOK, you've got a major misunderstanding...
The relational database model is built on the storage of sets - UNORDERED sets. In other words, when you hand a database a SELECT statement without an ORDER BY clause, the database is free to return the results in any order.
Now it so happens that most databases will happen to return data retrieved by an unordered SELECT, at least for a while, in the same order that it was inserted, especially if no UPDATE or DELETE activity has occured, and no database maintenance has occured. However, eventually most tables have some operation that creates a "space" in the underlying storage, or causes a row to expand and have to be moved or extended, or something. Then the database will start returning unordered results in a different order. If you (or other people) never ever ever UPDATE or DELETE a table, then on some databases the data might well come out in insertion order for a very very long time; given human nature and the way projects tend to work, relying on that is a sucker's bet, IMHO.
In other words, if you want the "most recent" something, you need to store a timestamp with your data. (With some databases, you might be able to take advantage of some non-standard feature to get "last updates" or "row change timestamps", but I know of no such for Postgres.
While this won't solve your major problem, above, your issue with rs.last is probably occuring because Postgres by default will prefetch your entire ResultSet. Use Statement.setFetchSize() to change that (PreparedStatement inherits the method, of course). -
Hi all,
i would to know if exists a standard way to paginate a large and dynamic ResultSet in a web application, with no open connection in session.
Another requirement is database independence. The ideal solution would be to have an scrollable and sensitive ResultSet with no long live connection open. Is possible to solve this issue with some pattern or specific jdbc extension?
Mauro.Hi,
you use MySql or another database.
My SQL could use start and end for a pagination. With oracle you need use Between rownum and rownun .
You must use the memory in order to put all you record in this memory.
You also could use a JDBC Cached driver ... -
Lion mouse scroll speed scrolling too fast
System Pref > Mouse > Scrolling Speed is set to the slowest level and it is still way too fast! Heard others complaining about this on a Parallels discussion group and thought I would post here. Incease the range of scrolling sensitivity in an update please! Reply to this post if you are having the same issue.
Scrolling was always way to fast in leopard when using Iphoto, but this with Lion it is too fast everywhere else except for huge files.I suppose you are using a non-Apple mouse. You will need to update the software, and adjust the tracking multiplier within the software.
Logitech just came out with an update for Lion. -
Performance issue - Result set
Hi,
I am facing performance problem with query execution. The code almost looks like this
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(0);
result = stmt.executeQuery("SELECT name, phoneNumber from tbluser inner join tblUserDetails ON tbluser.userid =tblUserDetails.userid WHERE ([phoneNumber] like'%123456789%') ORDER BY [name], [userID]");This query is taking too much time from the code.The same code is taking only few seconds for execution from the query analyzer.
when I changed the result set type to TYPE_SCROLL_SENSITIVE its performance improved significantly.
Please help me to find out y why a scroll sensitive result set performs better than a forward only result set?
CAn anybody help me how to use client side\server side cursors?
I have created indexes in tables. Is there any other way to improve the performance? Thanks in advance. Any help will be greatly appreciated.
Edited by: Aryan.s on Sep 16, 2008 7:49 PMOk, if you wait many rows in the select you change
stmt.setFetchSize(0);
to
stmt.setFetchSize(50);
Then, if you use "[phoneNumber] like" the database never used the index, you need tu use "=", ">" or "<", etc, if you want the database use the index, you never use "in", "exist", "like" or function "function(column) == variable", my suggestion is:
result = stmt.executeQuery(
"SELECT name, phoneNumber " +
"from tbluser inner join tblUserDetails ON tbluser.userid =tblUserDetails.userid " +
"WHERE ([phoneNumber] = '123456789') ORDER BY [name], [userID]");
And use a mask in the input of your application (JFormattedText) -
Having an issue with event handling - sql & java
HI all am trying to construct this hybrid of java and mysql. the data comes from a mysql database and I want it to display in the gui. this I have achieved thus far. However I have buttons that sort by surname, first name, ID tag etc....I need event handlers for these buttons but am quite unsure as to how to do it. any help would be much appreciated. Thanks in advance.
/* Student Contact Database GUI
* Phillip Wells
import java.awt.BorderLayout;
// imports java class. All import class statements tell the compiler to use a class that is defined in the Java API.
// Borderlayout is a layout manager that assists GUI layout.
import javax.swing.*; // imports java class. Swing enables the use of a GUI.
import javax.swing.JOptionPane; // imports java class. JOptionPane displays messages in a dialog box as opposed to a console window.
import javax.swing.JPanel; // imports java class. A component of a GUI.
import javax.swing.JFrame; // imports java class. A component of a GUI.
import javax.swing.JButton; // imports java class. A component of a GUI.
import javax.swing.JScrollPane; // imports java class. A component of a GUI.
import javax.swing.JTable; // imports java class. A component of a GUI.
import java.awt.*; // imports java class. Similar to Swing but with different components and functions.
import java.awt.event.*; // imports java class. Deals with events.
import java.awt.event.ActionEvent; // imports java class. Deals with events.
import java.awt.event.ActionListener; // imports java class. Deals with events.
import java.sql.*; // imports java class. Provides API for accessing and processing data stored in a data source.
import java.util.*; // imports java class. Contains miscellaneous utility classes such as strings.
public class studentContact extends JFrame { // public class declaration. The �public� statement enables class availability to other java elements.
private JPanel jContentPane; // initialises content pane
private JButton snam, id, fname, exit; // initialises Jbuttons
String firstname = "firstname"; //initialises String firstname
String secondname = "secondname"; //initialises String
public studentContact() {
Vector columnNames = new Vector(); // creates new vector object. Vectors are arrays that are expandable.
Vector data = new Vector();
initialize();
try {
// Connect to the Database
String driver = "com.mysql.jdbc.Driver"; // connect to JDBC driver
String url = "jdbc:mysql://localhost/Studentprofiles"; //location of Database
String userid = "root"; //user logon information for MySQL server
String password = ""; //logon password for above
Class.forName(driver); //reference to JDBC connector
Connection connection = DriverManager.getConnection(url, userid,
password); // initiates connection
// Read data from a table
String sql = "Select * from studentprofile order by "+ firstname;
//SQL query sent to database, orders results by firstname.
Statement stmt = connection.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//statement to create connection.
//Scroll sensitive allows movement forth and back through results.
//Concur updatable allows updating of database.
ResultSet rs = stmt.executeQuery(sql); // executes SQL query stated above and sets the results in a table
ResultSetMetaData md = rs.getMetaData(); // used to get the properties of the columns in a ResultSet object.
int columns = md.getColumnCount(); //
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i)); // Get column names
while (rs.next()) {
Vector row = new Vector(columns); // vectors data from table
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i)); // Get row data
data.addElement(row); // adds row data
rs.close();
stmt.close();
} catch (Exception e) { // catches exceptions
System.out.println(e); // prints exception message
JTable table = new JTable(data, columnNames) { //constructs JTable
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
return Object.class;
JScrollPane scrollPane = new JScrollPane( table ); // constructs scrollpane 'table'
getContentPane().add(new JScrollPane(table), BorderLayout.SOUTH); //adds table to a scrollpane
private void initialize() {
this.setContentPane(getJContentPane());
this.setTitle("Student Contact Database"); // sets title of table
ButtonListener b1 = new ButtonListener(); // constructs button listener
snam = new JButton ("Sort by surname"); // constructs Jbutton
snam.addActionListener(b1); // adds action listener
jContentPane.add(snam); //adds button to pane
id = new JButton ("Sort by ID"); // constructs Jbutton
id.addActionListener(b1); // adds action listener
jContentPane.add(id); //adds button to pane
fname = new JButton ("Sort by first name"); // constructs Jbutton
fname.addActionListener(b1); // adds action listener
jContentPane.add(fname); //adds button to pane
exit = new JButton ("Exit"); // constructs Jbutton
exit.addActionListener(b1); // adds action listener
jContentPane.add(exit); //adds button to pane
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel(); // constructs new panel
jContentPane.setLayout(new FlowLayout()); // sets new layout manager
return jContentPane; // returns Jcontentpane
private class ButtonListener implements ActionListener { // create inner class button listener that uses action listener
public void actionPerformed (ActionEvent e)
if (e.getSource () == exit) // adds listener to button exit.
System.exit(0); // exits the GUI
if (e.getSource () == snam)
if (e.getSource () == id)
if (e.getSource () == fname)
public static void main(String[] args) { // declaration of main method
studentContact frame = new studentContact(); // constructs new frame
frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //exits frame on closing
frame.setSize(600, 300); // set size of frame
frame.setVisible(true); // displays frame
}p.s. sorry about the untidy comments!OK, so you've got this code here:
private class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getSource () == exit) {
System.exit(0); // exits the GUI
if (e.getSource () == snam) {
if (e.getSource () == id) {
}Perfect fine way to do this; although I think creating anonymous would be a bit cleaner:
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
});But I think that the real question you have is "what do I put for logic when the JButtons are hit?", right?
I would answer that you want to dynamically build your SQL statement changing your ordering based on the button.
So you'd have a method that builds the SQL based on what you pass in - so it takes one argument perhaps?
private static final int NAME = 1;
ID = 2;
/* ... some code ... */
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
buildSQL(NAME);
/* ... some code ... */
private void buildSQL(int type) {
if ( type == NAME ) {
/* ... build SQL by name ... */
else if ( type == ID ) {
/* ... build SQL by id ... */
}That kind of thing.
Or you might choose to have several build methods with no parameter type; each building the SQL differently, and calling whichever one you need. I did not read your entire pgm, so I don't know how you'd want to organize it. You need to ask more specific questions at that point.
~Bill -
Having an issue with event handling - sql database & java gui
HI all, have posted this on another forum but I think this is the correct one to post on. I am trying to construct this hybrid of java and mysql. the data comes from a mysql database and I want it to display in the gui. this I have achieved thus far. However I have buttons that sort by surname, first name, ID tag etc....I need event handlers for these buttons but am quite unsure as to how to do it. any help would be much appreciated. Thanks in advance.
/* Student Contact Database GUI
* Phillip Wells
import java.awt.BorderLayout;
// imports java class. All import class statements tell the compiler to use a class that is defined in the Java API.
// Borderlayout is a layout manager that assists GUI layout.
import javax.swing.*; // imports java class. Swing enables the use of a GUI.
import javax.swing.JOptionPane; // imports java class. JOptionPane displays messages in a dialog box as opposed to a console window.
import javax.swing.JPanel; // imports java class. A component of a GUI.
import javax.swing.JFrame; // imports java class. A component of a GUI.
import javax.swing.JButton; // imports java class. A component of a GUI.
import javax.swing.JScrollPane; // imports java class. A component of a GUI.
import javax.swing.JTable; // imports java class. A component of a GUI.
import java.awt.*; // imports java class. Similar to Swing but with different components and functions.
import java.awt.event.*; // imports java class. Deals with events.
import java.awt.event.ActionEvent; // imports java class. Deals with events.
import java.awt.event.ActionListener; // imports java class. Deals with events.
import java.sql.*; // imports java class. Provides API for accessing and processing data stored in a data source.
import java.util.*; // imports java class. Contains miscellaneous utility classes such as strings.
public class studentContact extends JFrame { // public class declaration. The �public� statement enables class availability to other java elements.
private JPanel jContentPane; // initialises content pane
private JButton snam, id, fname, exit; // initialises Jbuttons
String firstname = "firstname"; //initialises String firstname
String secondname = "secondname"; //initialises String
public studentContact() {
Vector columnNames = new Vector(); // creates new vector object. Vectors are arrays that are expandable.
Vector data = new Vector();
initialize();
try {
// Connect to the Database
String driver = "com.mysql.jdbc.Driver"; // connect to JDBC driver
String url = "jdbc:mysql://localhost/Studentprofiles"; //location of Database
String userid = "root"; //user logon information for MySQL server
String password = ""; //logon password for above
Class.forName(driver); //reference to JDBC connector
Connection connection = DriverManager.getConnection(url, userid,
password); // initiates connection
// Read data from a table
String sql = "Select * from studentprofile order by "+ firstname;
//SQL query sent to database, orders results by firstname.
Statement stmt = connection.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//statement to create connection.
//Scroll sensitive allows movement forth and back through results.
//Concur updatable allows updating of database.
ResultSet rs = stmt.executeQuery(sql); // executes SQL query stated above and sets the results in a table
ResultSetMetaData md = rs.getMetaData(); // used to get the properties of the columns in a ResultSet object.
int columns = md.getColumnCount(); //
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnName(i)); // Get column names
while (rs.next()) {
Vector row = new Vector(columns); // vectors data from table
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i)); // Get row data
data.addElement(row); // adds row data
rs.close();
stmt.close();
} catch (Exception e) { // catches exceptions
System.out.println(e); // prints exception message
JTable table = new JTable(data, columnNames) { //constructs JTable
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
return Object.class;
JScrollPane scrollPane = new JScrollPane( table ); // constructs scrollpane 'table'
getContentPane().add(new JScrollPane(table), BorderLayout.SOUTH); //adds table to a scrollpane
private void initialize() {
this.setContentPane(getJContentPane());
this.setTitle("Student Contact Database"); // sets title of table
ButtonListener b1 = new ButtonListener(); // constructs button listener
snam = new JButton ("Sort by surname"); // constructs Jbutton
snam.addActionListener(b1); // adds action listener
jContentPane.add(snam); //adds button to pane
id = new JButton ("Sort by ID"); // constructs Jbutton
id.addActionListener(b1); // adds action listener
jContentPane.add(id); //adds button to pane
fname = new JButton ("Sort by first name"); // constructs Jbutton
fname.addActionListener(b1); // adds action listener
jContentPane.add(fname); //adds button to pane
exit = new JButton ("Exit"); // constructs Jbutton
exit.addActionListener(b1); // adds action listener
jContentPane.add(exit); //adds button to pane
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel(); // constructs new panel
jContentPane.setLayout(new FlowLayout()); // sets new layout manager
return jContentPane; // returns Jcontentpane
private class ButtonListener implements ActionListener { // create inner class button listener that uses action listener
public void actionPerformed (ActionEvent e)
if (e.getSource () == exit) // adds listener to button exit.
System.exit(0); // exits the GUI
if (e.getSource () == snam)
if (e.getSource () == id)
if (e.getSource () == fname)
public static void main(String[] args) { // declaration of main method
studentContact frame = new studentContact(); // constructs new frame
frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //exits frame on closing
frame.setSize(600, 300); // set size of frame
frame.setVisible(true); // displays frame
}OK, so you've got this code here:
private class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getSource () == exit) {
System.exit(0); // exits the GUI
if (e.getSource () == snam) {
if (e.getSource () == id) {
}Perfect fine way to do this; although I think creating anonymous would be a bit cleaner:
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
});But I think that the real question you have is "what do I put for logic when the JButtons are hit?", right?
I would answer that you want to dynamically build your SQL statement changing your ordering based on the button.
So you'd have a method that builds the SQL based on what you pass in - so it takes one argument perhaps?
private static final int NAME = 1;
ID = 2;
/* ... some code ... */
snam.addActionListener(new actionListener() {
public void actionPerformed(ActionEvent ae) {
buildSQL(NAME);
/* ... some code ... */
private void buildSQL(int type) {
if ( type == NAME ) {
/* ... build SQL by name ... */
else if ( type == ID ) {
/* ... build SQL by id ... */
}That kind of thing.
Or you might choose to have several build methods with no parameter type; each building the SQL differently, and calling whichever one you need. I did not read your entire pgm, so I don't know how you'd want to organize it. You need to ask more specific questions at that point.
~Bill -
How to order a updateable resulset?
hello
i use an updateable resulset.
everything works fine.
i can scroll forward, backward and can update it.
but when i add an "order by" to the select statement,
than i get following error:
ORA-01732: data manipulation operation not legal on this view
Cause: An attempt was made to use an UPDATE, INSERT, or DELETE statement on a view that contains expressions or functions or was derived from more than one table. If a join operation was used to create the view or the view contains virtual columns derived from functions or expressions, then the view may only be queried.
Action: UPDATE, INSERT, or DELETE rows in the base tables instead and restrict the operations on the view to queries.
now the question is, how can i order an updateabe resultset?
to use the scroll functionality, i must order the resultset,
otherwise i do not know in which order the resultset is ...
any idea?
thanks a lot!Hi useridlh,
As the error message (you posted) states, you are apparently attempting to update a database view that is based on more than one database table. Oracle does not allow this.
However, you claim that you are able to update the "ResultSet" if the query does not contain the ORDER BY clause. There are restrictions imposed by Oracle's JDBC drivers on updatable "ResultSet"s.
Unfortunately, I can't seem to access Oracle's online documentation, so I can't give you the URL, but the limitations are detailed in the JDBC Developer's Guide and Reference. I saw no mention in your post of which Oracle version you are using (nor which JDBC driver you are using),
so here is a quote from the Oracle 8i documentation:
In fact, you cannot use ORDER BY for any result set where you will want
to refetch rows. This applies to scroll-insensitive/updatable result
sets as well as scroll-sensitive result sets.
[Chapter 12 - Result Set Enhancements, page 12-10]
Hope this helps.
Good Luck,
Avi.
Maybe you are looking for
-
I have an application I'm submitting to our school website for potential students to fill out. There are sections for the student(s) to fill out as well as sections for staff to fill out. For the sake of security for the student filling out the form,
-
How do I get my downloads to open automatically, right now I have to find where my download folder is each time and then find the file I just downloaded. My download pop up screeen is also blank.
-
Journal Line can not drill down (Solved)
When I check one journal and want to dirlldown, the system said this function isn't available for my responsibility. Can someone help me on this and tell me where to assign the drilldown function to a responsibility? Edited by: Jerome.Yin on May 5, 2
-
Subcontracting process where Material Supplied by vendor
Hello Gurus, If anyone can provide me input how to map subcontracting scenario with subcontracting challan where some material is also added by vendor(Which is unknown at the time of raising purchase order). This additional componenet also attracts e
-
ICal Server running but not Running
I'm trying to get iCal server working. It looks as if it is running from within ServerAdmin but when I try to log in to iCal from Safari I keep getting the error Unable to Access calendar, because the calendar server is not running. Any help would be