When I do a insert in a remote tabke using jconnect it gives me the following error:
Unexpected exception : java.sql.SQLException: This transaction has been rolled back, rather than only the current statement.
, sqlstate = ZZZZZjava.sql.SQLException: This transaction has been rolled back, rather than only the current statement.
at com.sybase.jdbc4.jdbc.SybConnection.getAllExceptions(SybConnection.java:2780)
at com.sybase.jdbc4.jdbc.SybStatement.handleSQLE(SybStatement.java:2665)
at com.sybase.jdbc4.jdbc.SybStatement.nextResult(SybStatement.java:295)
at com.sybase.jdbc4.jdbc.SybStatement.nextResult(SybStatement.java:272)
at com.sybase.jdbc4.jdbc.SybStatement.updateLoop(SybStatement.java:2515)
at com.sybase.jdbc4.jdbc.SybStatement.executeUpdate(SybStatement.java:2499)
at com.sybase.jdbc4.jdbc.SybStatement.executeUpdate(SybStatement.java:577)
at connectSybase.main(connectSybase.java:48)
Do you know what it might be?
Here's my full code:
import java.io.*;
import java.sql.*;
public class connectSybase {
public static void main(String args[])
{
try
{
// jconn3 <-- do pessoal do OMS
//Class.forName("com.sybase.jdbc3.jdbc.SybDriver");
// jconn4 <-- do servidor de OMS1_PAR_DEV_SQL
Class.forName("com.sybase.jdbc4.jdbc.SybDriver");
}
catch (ClassNotFoundException cnfe)
{
System.out.println("BUM!");
}
try
{
System.out.println("Any of the following may throw an SQLException.");
System.out.println("Opening a connection.");
Connection con = java.sql.DriverManager.getConnection
("----------------------------");
// more code to use connection ...
System.out.println("Creating a statement object.");
Statement stmt = con.createStatement();
System.out.println("Executing the query.");
ResultSet rs = stmt.executeQuery("Select top 10 * from OMS_DEV..SCRIBE_AR");
System.out.println("Process the result set.");
while (rs.next())
{
System.out.println("Fetched value " + rs.getString(1));
}
System.out.println("Executing the query.");
int result = stmt.executeUpdate("---------------");
System.out.println("Process the result set: " + result );
}
catch (SQLException sqe)
{
sqe.printStackTrace();
System.out.println("Unexpected exception : " +
sqe.toString() + ", sqlstate = " +
sqe.getSQLState());
System.exit(1);
}
System.exit(0);
}
}
I've omitted the insert and the connection but both work because I get the result of the first select (only the insert fails) and the insert is also correct because it works using isql or dbartisan.
Sybase error message was not specific but the problem was related to packet size.
In ASE it was 8192 and in IQ only 2048.
It generated the error when the packet exceeded 2k.
Related
I've got a little problem when I'm running my query.
This is my code:
try {
// Class.forName("com.mysql.jdbc.Driver");
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
} catch (Exception ex) {
// handle the error
System.out.println("Driver issue: " + ex.getMessage());
System.out.println("Driver issue: " + ex.getClass().toString());
}
try {
// Do something with the Connection
System.out.println("Connection: " + conn);
Statement stmt = conn.createStatement();
ResultSet RS = stmt.executeQuery("show slave status");
...
try {
conn = DriverManager.getConnection("jdbc:mysql://" + internetPort + ":" + port + "/", username, password);
System.out.println("Connected to: " + internetPort);
return;
} catch (SQLException e) {
I realized that the script is connecting to DB, then execute query but the result is empty. When I'm doing the same query on mysql console then I got 1 result (correct result) I've even changed query "show slave status" to "show processlist" and still nothing. What's more, on my PC it's working correctly and executing query with correct result, but on other PC it doesn't. user and password is correct (the same i logged in console). Could anyone help me with that?
I have a little concern with Objet PreparedStatement in java to insert in an Oracle database.
Infect I prepare well the model of my INSERT query in the PreparedStatement I add well all my parameters with an addBatch() for each record I want to insert.
I add several batches to insert a 500 record hits for example.
Until then all of them work well I can insert what I want
On the other hand, in case my PreparedStatement generates a BatchUpdateException error (for example violation of constraint) on the 500 line that I want to insert it inserts me nothing at all.
I want to the limit remove the record that raises concern (with violation constraint) and insert at least the 499 line that are OK
How can I do that ? if she gives me a track I'd be grateful.
Just for Info I want to insert several lines of a stroke from 500 lines, so the solution to insert line by line does not fit me too much performance level.
Cordially
maybe this is not what you want but oracle has some built in error logic
you have to create an error table
e.g. if the table is called emp, run this
exec dbms_errlog.create_error_log(dml_table_name=>'emp');
that will create a table err$_emp that will catch the errors
then you can do something like this below(note the log errors into clause)
the batch will succeed and you will have to check the error table for errors after you run it
import java.sql.*;
public class Class1 {
public static void main(String[] args) throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PreparedStatement preparedStatement;
int records = 20;
try {
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#//host/db","scott","tiger");
String compiledQuery = "INSERT INTO EMP(EMPNO)" +
" VALUES" + "(?) LOG ERRORS INTO ERR$_EMP REJECT LIMIT UNLIMITED";
preparedStatement = connection.prepareStatement(compiledQuery);
for(int index = 1; index <= records; index++) {
preparedStatement.setInt(1, index);
preparedStatement.addBatch();
}
long start = System.currentTimeMillis();
int[] inserted;
try {
inserted = preparedStatement.executeBatch();
}
catch (SQLException e)
{
System.out.println("sql error");
}
long end = System.currentTimeMillis();
System.out.println("total time taken to insert the batch = " + (end - start) + " ms");
System.out.println("total time taken = " + (end - start)/records + " s");
preparedStatement.close();
connection.commit();
connection.close();
} catch (SQLException ex) {
System.err.println("SQLException information");
while (ex != null) {
System.err.println("Error msg: " + ex.getMessage());
ex = ex.getNextException();
}
throw new RuntimeException("Error");
}
}
}
As per my requirement, I need to pull records from Teradata db. While trying to pull data, I am getting exception as follows.
com.teradata.jdbc.jdbc_4.util.JDBCException: [Teradata Database] [TeraJDBC 14.10.00.09] [Error 3932] [SQLState 25000] Only an ET or null statement is legal after a DDL Statement.
at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDatabaseSQLException(ErrorFactory.java:307)
at com.teradata.jdbc.jdbc_4.statemachine.ReceiveInitSubState.action(ReceiveInitSubState.java:108)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:321)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:202)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:122)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.run(StatementController.java:113)
at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:380)
at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:322)
at com.teradata.jdbc.jdbc_4.TDStatement.doNonPrepExecuteQuery(TDStatement.java:310)
at com.teradata.jdbc.jdbc_4.TDStatement.executeQuery(TDStatement.java:1085)
at com.uprr.netcontrol.wkfl_mgmt.eventhandler.eventprocessor.TeradataSelectFromVolatileTable.main(TeradataSelectFromVolatileTable.java:26)
I think I got this exception because of using Volatile table in my query. But I need to use volatile table as part of query to make grouping on a particular column to get comma separated column data. Please, suggest me how to get result set while using volatile table in query. Here, I am enclosing sample java program to reproduce the exception.
package com.sample.package;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TeradataSelectFromVolatileTable {
public static void main(String[] args) throws SQLException {
String url = "jdbc:teradata://<TERADATA_TABLE_NAME>";
final String query =
"CREATE VOLATILE TABLE VT_TEMP AS (" + "SELECT PERS_ID,FIR_NAME FROM <TABLE_NAME> AS PERSON)"
+ "WITH DATA UNIQUE PRIMARY INDEX(PERS_ID) ON COMMIT PRESERVE ROWS;" + // volatile table created.
"SELECT * FROM VT_TEMP;"; // pulling rows.
Connection con = null;
try {
System.out.println(" Looking for the Teradata JDBC driver... ");
// Loading the Teradata JDBC driver
Class.forName("com.teradata.jdbc.TeraDriver");
System.out.println(" JDBC driver loaded. \n");
con = DriverManager.getConnection(url, "<USER_ID>", "<PASSWORD>");
Statement stmt = con.createStatement();
System.out.println(" Statement object created. \n");
ResultSet rset = stmt.executeQuery(query);
//Some operations on resultset goes here...........
System.out.println(" total column count " + rset.getMetaData().getColumnCount());
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the statement
con.close();
System.out.println("\n Connection object closed. \n");
}
}
}
I think you may need to wrap your CT statement in an explicit, Teradata-mode transaction to resolve the error you are receiving:
public class TeradataSelectFromVolatileTable {
public static void main(String[] args) throws SQLException {
String url = "jdbc:teradata://<TERADATA_TABLE_NAME>";
final String query =
"BT;" + // Begin Teradata-mode Transaction
"CREATE VOLATILE TABLE VT_TEMP AS (" +
"SELECT PERS_ID,FIR_NAME FROM <TABLE_NAME> AS PERSON)"
+ "WITH DATA UNIQUE PRIMARY INDEX(PERS_ID) ON COMMIT PRESERVE ROWS;" + // volatile table created. +
"ET;" + // End Teradata-mode Transaction
"SELECT * FROM VT_TEMP;"; // pulling rows.
Connection con = null;
try {
System.out.println(" Looking for the Teradata JDBC driver... ");
// Loading the Teradata JDBC driver
Class.forName("com.teradata.jdbc.TeraDriver");
System.out.println(" JDBC driver loaded. \n");
con = DriverManager.getConnection(url, "<USER_ID>", "<PASSWORD>");
Statement stmt = con.createStatement();
System.out.println(" Statement object created. \n");
ResultSet rset = stmt.executeQuery(query);
//Some operations on resultset goes here...........
System.out.println(" total column count " + rset.getMetaData().getColumnCount());
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the statement
con.close();
System.out.println("\n Connection object closed. \n");
}
}
}
I keep getting the SQLITE_BUSY database file is locked error. I have looked on other posts, but none have solved this issue. Can't seem to figure out why this error is occurring. I know that you are only supposed to have one connection at a time, but it appears that I do only have one connection. Any ideas? Does it have something to do with the fact that object Connection connection is initialized as null then reset? Thats the only thing I could think of, however if I take it away, then I am not able to close the connection in the finally block.
public class GetChromeHistory
{
public static void main (String[] args)
{
Connection connection= null;
ResultSet resultSet = null;
Statement statement = null;
try
{
// We think, but are not sure, that the line below registers the sqlite drive with JDBC.
Class.forName("org.sqlite.JDBC");
connection = DriverManager
.getConnection("jdbc:sqlite:db.db");
statement = connection.createStatement();
//problem occurs on line below, database file is locked
resultSet = statement
.executeQuery("SELECT * FROM urls where visit_count > 0");
while(resultSet.next())
{
//eventually save into a set or list
System.out.println ("URL [" + resultSet.getString("url") + "]" +
", visit count [" + resultSet.getString("visit_count") + "]");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
resultSet.close();
statement.close();
connection.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
I've got a following problem: I'm trying to insert data (in this case a username) into a table using the following code:
void AddNewUser(String name, Connection conn){
if(ret == null){
ret = new DB_Retriever(conn);
}
if(!ret.UserExists(name, conn)){
try{
Statement stm = conn.createStatement();
stm.executeUpdate(DB_OperationalData.insert_new_user[0][0] + name + DB_OperationalData.insert_new_user[0][1]);
stm.executeUpdate(DB_OperationalData.insert_new_user[1][0] + name + DB_OperationalData.insert_new_user[1][1]);
stm.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
By the way: It absolutely doesn't matter what I put in the catch clause, nothing that I put there is executed. Just to make everything clear, here is the content of the DB_OperationalData.insert_new_user String array:
public static final String[][] insert_new_user = {
{"INSERT INTO User (Username, Status) VALUES ('","','IN');"},
{"INSERT INTO Statistics (Player_ID) SELECT ID FROM User WHERE Username='","';"}};
The second statement is supposed to copy the ID of the user that is inserted and put it into Player_ID field of the Statistics table (Table User's ID is an autonumbered field).
The exception I get is:
Error while processing the query: java.sql.SQLException: ResultSet closed
What is interesting, is that it works and the data is added correctly but I simply do not want any exceptions thrown.
That's the console output I get:
This is 'data' Package Testing class
Connection to the database established.
The number of tables existing in the database is: 0
All the queries have been processed successfully
Adding new users:
Error while processing the query: java.sql.SQLException: ResultSet closed
All the lines above the Exception are my own printouts, so I know what has actually happened.
[EDIT]
I have changed the code to use the PreparedStatement instead of ordinary Statement and the current try clause looks as follows:
PreparedStatement pstm = conn.prepareStatement(DB_OperationalData.insert_new_user[0]);
pstm.setString(1, name);
pstm.addBatch();
conn.setAutoCommit(false);
pstm.executeBatch();
conn.setAutoCommit(true);
pstm.close();
And the output is (still regardless of the contents of the catch clause):
This is 'data' Package Testing class
Connection to the database established.
The number of tables existing in the database is: 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at org.sqlite.PrepStmt.batch(PrepStmt.java:173)
at org.sqlite.PrepStmt.setString(PrepStmt.java:254)
at data.DB_Writer.AddNewUser(DB_Writer.java:28)
at data.DataHandler.AddNewUser(DataHandler.java:94)
at data.Tester.main(Tester.java:18)
All the queries have been processed successfully
Adding new users:
Error while processing the query: java.sql.SQLException: ResultSet closed
[EDIT 2]
With regards to the original version, when I remove the stm.close(); there is absolutely no difference and I still get the 'ResultSet closed' Exception.
[EDIT 3]
Here is the code of the method that is calling the above:
public void AddNewUser(String username)throws IllegalUsernameException{
if(username.length()==0 || username.length()>20){
throw new IllegalUsernameException();
}
writer.AddNewUser(username, conn);
}
The connection to the database is established by this class:
class DB_Connection {
public static Connection getConnection(){
Connection conn = null;
try{
Class.forName("org.sqlite.JDBC");
}
catch(ClassNotFoundException e){
log("Error while loading the database driver: " + e);
return null;
}
try{
conn = DriverManager.getConnection("jdbc:sqlite:database.db");
}
catch(SQLException e){
log("Unable to connect to the database: " + e);
return null;
}
return conn;
}
public static void log(String msg){
System.out.println(msg);
}
}
The DB_Retriever's method that is checking for the existing username:
boolean UserExists(String name, Connection conn){
String result = "";
try{
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(DB_OperationalData.user_exists[0] + name + DB_OperationalData.user_exists[1]);
result = rs.getString("Username");
}
catch(SQLException e){
System.out.println("Error while processing the query: " + e);
}
if(result.equals(name)){
return true;
}
return false;
}
The only location where Error while processing the query: java.sql.SQLException: ResultSet closed could be printed to the console is in UserExists(..), unless there is another method with a similar catch block. Indeed the ResultSet is not used correctly in UserExists, what may cause the error.
For a more complete description of how to work with JDBC look at this answer or the JDBC documentation. A possible alternative to the existing UserExists is:
boolean userExists(String name, Connection conn) {
PreparedStatement stmt = null;
try{
stmt = conn.prepareStatement("SELECT COUNT(Username) FROM User WHERE Username = ?");
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
rs.next(); // set cursor to first row
int count = rs.getInt(1);
rs.close();
return count > 0;
} catch(SQLException e) {
// propagate error
throw new RuntimeException(e);
} finally {
// clean up resources
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ignore) {
log("error on sql clean up", ignore);
}
}
}
}