JDBC问题,为什么我的TYPE_SCROLL_SENSITIVE和TYPE_SCROLL_INSENSITIVE不起效果?

ejay 2009-05-18 10:19:10
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame{

JButton jb = new JButton();

static ResultSet rs = null;
static Statement stmt = null;
static Connection conn = null;
public Main(){
this.setTitle("Test");
this.setBounds(200, 200, 400, 200);
this.setLayout(null);
jb.setText("OK");
jb.setBounds(100, 100, 60, 30);
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
call();
}
});
this.add(jb);
this.setVisible(true);
}

public void call(){
try{
String id = rs.getString("EXAMID");
String name = rs.getString("NAME");
int age = rs.getInt("AGE");
System.out.println(id + ": " + name + " " + age);
}catch(Exception ex){
ex.printStackTrace();
}
}

public static void main(String[] args) {
try {
new Main();
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:XE", "sa", "sa");
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select * from SYS.STUBINFOX");

rs.next();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

上面的代码用来测试TYPE_SCROLL_SENSITIVE参数,我修改数据库以后,再点击一下按钮,可是打印出来的没有改变,不是说TYPE_SCROLL_SENSITIVE对修改是敏感的吗?昨天晚上在家测试连接ACCESS(家里机器装不了Oracle),结果恰好相反,无论是TYPE_SCROLL_SENSITIVE参数还是TYPE_SCROLL_INSENSITIVE都敏感,只要数据库一修改,打印的结果马上就跟着修改。完全没有头绪,请教给予支持!!!谢谢!!!!!!
...全文
300 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuyujian 2011-12-14
  • 打赏
  • 举报
回复
请问一下,Access是否不支持的TYPE_SCROLL_SENSITIVE和TYPE_CONCUR_UPDATABLE,这两种游标,我一使用这两个参数得到的ResultSet,就取不到数据集
wuyujian 2011-12-14
  • 打赏
  • 举报
回复
请问一下,Access是否不支持的TYPE_SCROLL_SENSITIVE和TYPE_CONCUR_UPDATABLE,这两种游标,我一使用这两个参数得到的ResultSet,就取不到数据集
wuyujian 2011-12-14
  • 打赏
  • 举报
回复
请问一下,Access是否不支持的TYPE_SCROLL_SENSITIVE和TYPE_CONCUR_UPDATABLE,这两种游标,我一使用这两个参数得到的ResultSet,就取不到数据集
dieyingao 2009-06-09
  • 打赏
  • 举报
回复
MARK一下。。。
铁匠梁老师 2009-06-09
  • 打赏
  • 举报
回复
学习了。顺便回帖是一种美德!每天回帖即可获得 10 分可用分!
machao299 2009-06-09
  • 打赏
  • 举报
回复
Up java 超级群 :有时间大家共同交流 51177847
judebaby 2009-06-08
  • 打赏
  • 举报
回复
学习了
zhaoqiang415362381 2009-06-02
  • 打赏
  • 举报
回复
Access不支持吧
wibnmo 2009-05-31
  • 打赏
  • 举报
回复
up now.
lixj2009 2009-05-31
  • 打赏
  • 举报
回复
这个事JDBC2.0新特性,Access不支持
xnjnmn 2009-05-18
  • 打赏
  • 举报
回复
2.TYPE_SCROLL_INSENSITIVE,双向滚动,但不及时更新,就是如果数据库里的数据修改过,并不在ResultSet中反应出来。
3.TYPE_SCROLL_SENSITIVE,双向滚动,并及时跟踪数据库的更新,以便更改ResultSet中的数据
http://blog.csdn.net/axman/archive/2009/03/12/3984103.aspx
这个问题我在几年前说过,但今天再次从CSDN上看到有人问这个问题,可以看出,真正懂这个问题的人1%都不到。
我再次把这个问题写在这里,希望光临我的BLOG的人能真正了解它。

我们先来做一个例子,在例子中我用的是mysql-essential-5.1.30-win32版。

来跟我做以下几个命令:

mysql> create database axman;
mysql> use axman;
mysql> create table axmantest(
-> id int(4) not null auto_increment primary key
-> name varchar(20));

mysql> insert into axmantest (name) values ('axman')
mysql> insert into axmantest (name) values ('sager')
mysql> insert into axmantest (name) values ('p4');

OK,写一个测试程序:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class MainTest {
public static void main(String[] args) throws Exception{

Class.forName("org.gjt.mm.mysql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/axman?useUnicode=true&characterEncoding=UTF-8","root","password");
Statement stmt = conn.createStatement(ResultSet.CONCUR_UPDATABLE, ResultSet.TYPE_SCROLL_SENSITIVE);
ResultSet rs = stmt.executeQuery("select * from axmantest");
System.out.println("请删除!");
Thread.sleep(1000*20);
while(rs.next()){
System.out.println(rs.getString(1)+","+rs.getString(2));
}
rs.close();
stmt.close();
conn.close();
}
}

先在刚才的MYSQL命令环境下输入命令:
select * from axmantest;
+----+-------+
| id | name |
+----+-------+
| 1 | axman |
| 2 | sager |
| 3 | p4 |
+----+-------+
3 rows in set (0.00 sec)

delete from axmantest where id = 3;不要提交,敲好放在这儿,运行那个测试程序。看到“请删除”三个字立即切换到
Mysql命令环境下回车。
跟着:
select * from axmantest;
+----+-------+
| id | name |
+----+-------+
| 1 | axman |
| 2 | sager |
+----+-------+
2 rows in set (0.00 sec)

回到测试程序,看看:
1,axman
2,sager
3,p4

我的个神啦,这哪叫结果集敏感啊?完全是INSENSITIVE嘛!


但是,这正是TYPE_SCROLL_SENSITIVE造成的。

对于TYPE_SCROLL_INSENSITIVE,一次查询的结果可能存在数据库端的内存缓冲中,也可以直接发送到JVM的内存中,
如果结果集很小,会直接发送到JVM层,然后被next定位,转换数据类型,显示,或者缓存在数据库内存中。总之
查询结果已经和数据库脱离,这时如果数据库记录被其它进程更新,则结果集无法得知,还是使用缓存的记录。

而对于TYPE_SCROLL_SENSITIVE,一次查询的结果并不是直接的记录被缓存下来,只是符合条件的记录的“原始ROWID”
被缓存了,这个原始ROWID并非特指ORACLE的ROWID,而是数据库底层定位记录的索引值。简单说
select * from axmantest操作的结果并不是
1,axman
2,sager
3,p4
这些内容被缓存了。而是类似rd_file_offset_0x111010101001这样的值被缓存了,然后next定位到这条记录时,
数据库会再次根据这个ROWID做底层操作:
select * from axmantest where rowid = rd_file_offset_0x111010101001;
简单说每next一次都会发生一次查询,这样可以保证next后操作到的是当前最新的数据。
对于更新操作,如果你先查询,然后数据被其它进程更新掉了,然后next到这条记录时肯定没有问题,会取出最新的
内容,但对于删除操作。因为数据库删除记录只是记录上做一个标记,不再被检索,但原来被缓存的ROWID还在,根据
它还可以通过数据库自己的底层操作正确地把数据提取出来,所以你看到的已经被手工删除的数据又被显示出来了。

同样插入操作因为查询的时候结果集中还没有要插入的操作,所以不可能缓存了它的ROWID,我们再次做这个例子,把
“请删除”修改成“请插入”(有些不好听),现在数据库中是两条记录,当运行程序看到“请插入”时立即手工插入,注意
是往表中插入记录,不是插入别的。然后看一下运行结果还是两条记录。

如果有兴趣再试一下更新操作,你会看更新的结果会马上反映出来。

所以TYPE_SCROLL_SENSITIVE只能更新操作敏感,其它的插入操作和删除操作不会及时地反映到结果集中。
KingZChina 2009-05-18
  • 打赏
  • 举报
回复
http://blog.csdn.net/axman/archive/2009/03/12/3984103.aspx
package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具类 * * * Description: 将大部分的数据库操作放入这个类中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之类的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具类, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧