下面列出了java.sql.SQLException#toString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void execute(TestContext testContext) throws IOException {
Statement stmt =
(PreparedStatement) testContext.getCurrentStatement();
if (stmt == null) {
testContext.storeMessage("No current statement");
} else if (stmt instanceof PreparedStatement) {
try {
ResultSetMetaData metadata =
((PreparedStatement) stmt).getMetaData();
for (int i = 1; i <= metadata.getColumnCount(); i++) {
testContext.storeMessage(
metadata.getColumnName(i) + ": "
+ metadata.getColumnTypeName(i));
}
} catch (SQLException e) {
throw new IllegalStateException(e.toString());
}
}
}
private void addEntry(InterceptorChain chain, Entry entry, Connection con)
throws LDAPException {
try {
// begin the transaction
HashMap<String,String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + this.dbInsertName);
String uid = ((RDN) (new DN(entry.getEntry().getDN())).getRDNs().get(0)).getValue();
insertRecord(entry.getEntry().getAttributeSet(), con, db2ldap, uid,false);
} catch (SQLException e) {
try {
con.rollback();
} catch (SQLException e1) {
throw new LDAPException("Could not delete entry or rollback transaction",LDAPException.OPERATIONS_ERROR,e.toString(),e);
}
throw new LDAPException("Could not delete entry",LDAPException.OPERATIONS_ERROR,e.toString(),e);
}
}
@Override
public int read(byte[] b) throws IOException {
if (this.currentPositionInBlob + 1 > this.length) {
return -1;
}
try {
byte[] asBytes = getBytesInternal(this.pStmt, (this.currentPositionInBlob) + 1, b.length);
if (asBytes == null) {
return -1;
}
System.arraycopy(asBytes, 0, b, 0, asBytes.length);
this.currentPositionInBlob += asBytes.length;
return asBytes.length;
} catch (SQLException sqlEx) {
throw new IOException(sqlEx.toString());
}
}
public static List<Block> getGeneratedBlocks(Long accountId) {
Connection con = null;
try {
con = Db.getConnection();
PreparedStatement pstmt = con
.prepareStatement("SELECT * FROM block WHERE generator_id = ? ORDER BY db_id ASC");
pstmt.setLong(1, accountId);
List<Block> result = new ArrayList<Block>();
DbIterator<? extends Block> iterator = Nxt.getBlockchain().getBlocks(con,
pstmt);
while (iterator.hasNext()) {
result.add(iterator.next());
}
return result;
}
catch (SQLException e) {
DbUtils.close(con);
throw new RuntimeException(e.toString(), e);
}
}
public void stopServer() {
if (server != null) {
log.info("正在关闭H2 database...端口号:" + port);
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException("关闭H2 database连接出错:" + e.toString(), e);
}
server.shutdown();
server.stop();
log.info("关闭H2 database成功...端口号:" + port);
}
}
public void delete(DeleteInterceptorChain chain, DistinguishedName dn,
LDAPConstraints constraints) throws LDAPException {
Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName);
if (con == null) {
throw new LDAPException("Operations Error",LDAPException.OPERATIONS_ERROR,"No Database Connection");
}
try {
// begin the transaction
con.setAutoCommit(false);
String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue();
PreparedStatement ps = con.prepareStatement(this.deleteSQL);
ps.setString(1, uid);
ps.executeUpdate();
con.commit();
} catch (SQLException e) {
try {
con.rollback();
} catch (SQLException e1) {
throw new LDAPException("Could not delete entry or rollback transaction",LDAPException.OPERATIONS_ERROR,e.toString(),e);
}
throw new LDAPException("Could not delete entry",LDAPException.OPERATIONS_ERROR,e.toString(),e);
}
}
public void testBug42488() throws Exception {
System.clearProperty(GfxdConstants.GFXD_DISABLE_STATEMENT_MATCHING);
SelectQueryInfo.setTestFlagIgnoreSingleVMCriteria(true);
Connection conn = getConnection();
Statement s = conn.createStatement();
s.execute("create table TESTTABLE (ID int not null , "
+ "DESCRIPTION varchar(1024) , ADDRESS varchar(1024))");
String query1 = "Select * from TESTTABLE where ID >= 1 ";
String query2 = "Select * from TESTTABLE where ID >= 2 ";
s.executeUpdate("insert into testtable values(1,'1','1')");
GemFireXDQueryObserver old = null;
try {
//old = GemFireXDQueryObserverHolder .setInstance(new GemFireXDQueryObserverAdapter() {});
try {
s.executeQuery(query1);
s.executeQuery(query2);
}
catch (SQLException e) {
throw new SQLException(e.toString()
+ " Exception in executing query = " + query1, e.getSQLState());
}
//assertTrue(this.callbackInvoked);
}
finally {
if (old != null) {
GemFireXDQueryObserverHolder.setInstance(old);
}
}
}
public void delete(DeleteInterceptorChain chain, DistinguishedName dn,
LDAPConstraints constraints) throws LDAPException {
Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName);
if (con == null) {
throw new LDAPException("Operations Error",LDAPException.OPERATIONS_ERROR,"No Database Connection");
}
try {
// begin the transaction
con.setAutoCommit(false);
String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue();
PreparedStatement ps = con.prepareStatement(this.deleteSQL);
ps.setString(1, uid);
ps.executeUpdate();
con.commit();
} catch (SQLException e) {
try {
con.rollback();
} catch (SQLException e1) {
throw new LDAPException("Could not delete entry or rollback transaction",LDAPException.OPERATIONS_ERROR,e.toString(),e);
}
throw new LDAPException("Could not delete entry",LDAPException.OPERATIONS_ERROR,e.toString(),e);
}
}
public void delete(DeleteInterceptorChain chain, DistinguishedName dn,
LDAPConstraints constraints) throws LDAPException {
Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName);
if (con == null) {
throw new LDAPException("Operations Error",LDAPException.OPERATIONS_ERROR,"No Database Connection");
}
try {
// begin the transaction
con.setAutoCommit(false);
String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue();
PreparedStatement ps = con.prepareStatement(this.deleteSQL);
ps.setString(1, uid);
ps.executeUpdate();
con.commit();
} catch (SQLException e) {
try {
con.rollback();
} catch (SQLException e1) {
throw new LDAPException("Could not delete entry or rollback transaction",LDAPException.OPERATIONS_ERROR,e.toString(),e);
}
throw new LDAPException("Could not delete entry",LDAPException.OPERATIONS_ERROR,e.toString(),e);
}
}
private String createErrorMessage(SQLException e) {
String err = e.toString();
if (e.getCause() != null) {
err = err + ", " + e.getCause().toString();
}
return err;
}
@Override
public void close() throws IOException {
if (this.pStmt != null) {
try {
this.pStmt.close();
} catch (SQLException sqlEx) {
throw new IOException(sqlEx.toString());
}
}
super.close();
}
/**
* Tests if the update works correctly if it has parameterized where clause with
* region.put convertible case
*/
public void testParameterizedRegionPutConvertibleUpdate_Bug39652() throws Exception {
Connection conn = getConnection();
Statement s = conn.createStatement();
s.execute("create table TESTTABLE (ID int primary key , "
+ "DESCRIPTION varchar(1024) , ADDRESS varchar(1024), type int)");
String query = "Update TESTTABLE set type = ? where ID = 1 ";
GemFireXDQueryObserver old = null;
try {
old = GemFireXDQueryObserverHolder
.setInstance(new GemFireXDQueryObserverAdapter() {
@Override
public void queryInfoObjectFromOptmizedParsedTree(QueryInfo qInfo, GenericPreparedStatement gps, LanguageConnectionContext lcc) {
if (qInfo instanceof UpdateQueryInfo) {
callbackInvoked = true;
}
}
});
// Now insert some data
this.callbackInvoked = false;
s.executeUpdate("insert into TESTTABLE values (1, 'First', 'J 604',1)");
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, 2);
try {
int n = ps.executeUpdate();
assertEquals(n,1);
}
catch (SQLException e) {
e.printStackTrace();
throw new SQLException(e.toString()
+ " Exception in executing query = " + query, e.getSQLState());
}
assertTrue(this.callbackInvoked);
}
finally {
if (old != null) {
GemFireXDQueryObserverHolder.setInstance(old);
}
}
}
boolean getAutoCommit() throws DataAccessPointException {
boolean result = false;
try {
result = conn.getAutoCommit();
} catch (SQLException e) {
throw new DataAccessPointException(e.toString());
}
return result;
}
void setAutoCommit(boolean flag) throws DataAccessPointException {
try {
conn.setAutoCommit(flag);
} catch (SQLException e) {
throw new DataAccessPointException(e.toString());
}
}
/**
* Validates that QueryInfo does not get created repeatedly if the
* query string is unchanged, with same Statement object
* @throws SQLException
*/
public void testRegionGetMultipleTimesWithSameStmnt() throws SQLException {
Connection conn = getConnection();
createTableWithPrimaryKey(conn);
String query = "Select * from orders where id =8";
GemFireXDQueryObserver old = null;
try {
old = GemFireXDQueryObserverHolder
.setInstance(new GemFireXDQueryObserverAdapter() {
@Override
public void queryInfoObjectFromOptmizedParsedTree(QueryInfo qInfo, GenericPreparedStatement gps, LanguageConnectionContext lcc) {
callbackInvoked = true;
++index;
}
});
// Creating a statement object that we can use for running various
// SQL statements commands against the database.
conn = getConnection();
final int numExecution = 5;
Statement s = conn.createStatement();
for (int i = 0; i < numExecution; ++i) {
try {
s.executeQuery(query);
}
catch (SQLException e) {
throw new SQLException(e.toString()
+ " Exception in executing query = " + query, e
.getSQLState());
}
}
assertTrue(this.callbackInvoked);
assertEquals(1,index);
}
finally {
if (old != null) {
GemFireXDQueryObserverHolder.setInstance(old);
}
}
}
public void testInconvertibleToGetQuery() throws Exception {
Connection conn = getConnection();
createTableWithPrimaryKey(conn);
String[] queries = new String[] { "Select * from orders where id > 8"
/* "Select * from orders where id = 8 and cust_name = 'asif'" */};
GemFireXDQueryObserver old = null;
try {
old = GemFireXDQueryObserverHolder
.setInstance(new GemFireXDQueryObserverAdapter() {
private int index = 0;
@Override
public void queryInfoObjectFromOptmizedParsedTree(QueryInfo qInfo, GenericPreparedStatement gps, LanguageConnectionContext lcc) {
QueryInfoTest.this.callbackInvoked = true;
assertNotNull(qInfo.getRegion());
++index;
}
});
// Creating a statement object that we can use for running various
// SQL statements commands against the database.
Statement s = conn.createStatement();
for (int i = 0; i < queries.length; ++i) {
try {
s.executeQuery(queries[i]);
}
catch (SQLException e) {
throw new SQLException(e.toString()
+ " Exception in executing query = " + queries[i], e
.getSQLState());
}
}
assertTrue(this.callbackInvoked);
}
finally {
if (old != null) {
GemFireXDQueryObserverHolder.setInstance(old);
}
}
}
/**
* Validates that PreparedStatement execution reuses the original Activation
* @throws SQLException
*/
public void testRegionGetMultipleTimesWithPrepStmnt() throws SQLException {
Connection conn = getConnection();
createTableWithPrimaryKey(conn);
String query = "Select * from orders where id =?";
GemFireXDQueryObserver old = null;
try {
old = GemFireXDQueryObserverHolder
.setInstance(new GemFireXDQueryObserverAdapter() {
private AbstractGemFireActivation origAct = null;
@Override
public void beforeGemFireResultSetExecuteOnActivation(
AbstractGemFireActivation activation) {
if (index == 0) {
origAct = activation;
}
else {
assertEquals(activation, origAct);
}
++index;
}
@Override
public void queryInfoObjectFromOptmizedParsedTree(QueryInfo qInfo, GenericPreparedStatement gps, LanguageConnectionContext lcc) {
callbackInvoked = true;
}
});
// Creating a statement object that we can use for running various
// SQL statements commands against the database.
conn = getConnection();
final int numExecution = 5;
PreparedStatement ps = conn.prepareStatement(query);
for (int i = 0; i < numExecution; ++i) {
try {
ps.setInt(1,i);
ps.executeQuery();
}
catch (SQLException e) {
throw new SQLException(e.toString()
+ " Exception in executing query = " + query, e
.getSQLState());
}
}
assertTrue(this.callbackInvoked);
assertEquals(numExecution,index);
}
finally {
if (old != null) {
GemFireXDQueryObserverHolder.setInstance(old);
}
}
}
/**
* Runs a custom SQL statement to check the size of the message body
*/
@Override
public synchronized long getMessageSize() throws IOException {
if (size != -1) {
return size;
}
if (retrieveMessageBodySizeSQL == null) {
// There was no SQL statement for this repository... figure it out
// the hard way
System.err.println("no SQL statement to find size");
return size = super.getMessageSize();
}
Connection conn = null;
PreparedStatement retrieveMessageSize = null;
ResultSet rsRetrieveMessageSize = null;
try {
conn = repository.getConnection();
retrieveMessageSize = conn.prepareStatement(retrieveMessageBodySizeSQL);
retrieveMessageSize.setString(1, key);
retrieveMessageSize.setString(2, repository.repositoryName);
rsRetrieveMessageSize = retrieveMessageSize.executeQuery();
if (!rsRetrieveMessageSize.next()) {
throw new IOException("Could not find message");
}
size = rsRetrieveMessageSize.getLong(1);
InputStream in = null;
try {
if (sr != null) {
if (sr instanceof org.apache.james.repository.file.FilePersistentStreamRepository) {
size += ((org.apache.james.repository.file.FilePersistentStreamRepository) sr).getSize(key);
} else {
in = sr.get(key);
int len;
byte[] block = new byte[1024];
while ((len = in.read(block)) > -1) {
size += len;
}
}
}
} catch (Exception e) {
// ignore this... either sr is null, or the file does not exist
// or something else
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ioe) {
// Ignored - no access to logger at this point in the code
}
}
return size;
} catch (SQLException sqle) {
throw new IOException(sqle.toString());
} finally {
theJDBCUtil.closeJDBCResultSet(rsRetrieveMessageSize);
theJDBCUtil.closeJDBCStatement(retrieveMessageSize);
theJDBCUtil.closeJDBCConnection(conn);
}
}
public void start(Xid xid, int flags) throws XAException {
// Comment out following debug statement before public release:
/*
System.err.println("STARTING NEW Xid: " + xid);
*/
if (state != XA_STATE_INITIAL && state != XA_STATE_DISPOSED
&& state != XA_STATE_ENDED) {
throw new XAException("Invalid XAResource state");
}
if (xaDataSource == null) {
throw new XAException(
"JDBCXAResource has not been associated with a XADataSource");
}
if (xid == null) {
// This block asserts that all JDBCXAResources with state
// >= XA_STATE_STARTED have a non-null xid.
throw new XAException("Null Xid");
}
try {
if (connection.getAutoCommit()) {
originalAutoCommitMode = true; // real/phys.
connection.setAutoCommit(false); // real/phys.
}
} catch (SQLException se) {
throw new XAException(se.toString());
}
if (!xid.equals(this.xid)) {
this.xid = xid;
xaDataSource.addResource(this.xid, this);
}
state = XA_STATE_STARTED;
// N.b. The DataSource does not have this XAResource in its list
// until right here. We can't tell DataSource before our start()
// method, because we don't know our Xid before now.
}
public void testInconvertibleToGetQuery() throws Exception {
Connection conn = getConnection();
createTableWithPrimaryKey(conn);
String[] queries = new String[] { "Select * from orders where id > 8"
/* "Select * from orders where id = 8 and cust_name = 'asif'" */};
GemFireXDQueryObserver old = null;
try {
old = GemFireXDQueryObserverHolder
.setInstance(new GemFireXDQueryObserverAdapter() {
private int index = 0;
@Override
public void queryInfoObjectFromOptmizedParsedTree(QueryInfo qInfo, GenericPreparedStatement gps, LanguageConnectionContext lcc) {
QueryInfoTest.this.callbackInvoked = true;
assertNotNull(qInfo.getRegion());
++index;
}
});
// Creating a statement object that we can use for running various
// SQL statements commands against the database.
Statement s = conn.createStatement();
for (int i = 0; i < queries.length; ++i) {
try {
s.executeQuery(queries[i]);
}
catch (SQLException e) {
throw new SQLException(e.toString()
+ " Exception in executing query = " + queries[i], e
.getSQLState());
}
}
assertTrue(this.callbackInvoked);
}
finally {
if (old != null) {
GemFireXDQueryObserverHolder.setInstance(old);
}
}
}