SQL Server, JTDS causes java.sql.SQLException: Invalid state, the ResultSet object is closed - sql

I am using Tomcat 7, Microsoft SQL Server 2008 RC2 and JTDS driver
I am actually using C3P0 as well to try and solve this problem, but it makes no difference at all. I was using Microsoft's driver but it caused me other problems (the requested operation is not supported on forward only result sets)
I get the following error, always at the same point. I have successfully run other queries before getting to this point:
java.sql.SQLException: Invalid state, the ResultSet object is closed.
at
net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:287)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.findColumn(JtdsResultSet.java:943)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.getInt(JtdsResultSet.java:968)
at
com.mchange.v2.c3p0.impl.NewProxyResultSet.getInt(NewProxyResultSet.java:2573)
at com.tt.web.WebPosition.createPosition(WebPosition.java:863)
The code is as follows:
public static List getListPositions(String query) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List list = null;
try { //execute the sql query and create the resultSet
con = DBConnection.getInstance().getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()) {
if(rs.isFirst()) {
list = new ArrayList();
}
WebPosition webPos = null;
webPos = new WebPosition(rs);
list.add(webPos);
}
} catch (java.sql.SQLException e) {
System.out.println("SQLException in getListPositions");
System.out.print(query);
Log.getInstance().write(query);
Log.getInstance().write(e.toString());
} catch (Exception ex) {
System.out.print(ex);
ex.printStackTrace();
Log.getInstance().write(ex.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
DBConnection.getInstance().returnConnection(con);
}
return list;
}
public WebPosition(ResultSet rs) {
createPosition( rs);
}
public void createPosition(ResultSet rs) {
try {
this.setCurrentDate4Excel(rs.getString("SYSDATE_4_EXCEL"));
this.setExerciseType(rs.getInt("EXERCISE_STYLE_CD"));
...
The code fails in between the above two lines.
I am at a loss to explain why the Result set would be closed in the middle of a function (i.e. it would retrieve rs.getString("SYSDATE_4_EXCEL") but then fail with the error posted at the line rs.getInt("EXERCISE_STYLE_CD"))
Does anyone have any ideas? I imagine that it is some kind of memory issue, and that the connection is automatically closed after a certain amount of data, but I am not sure how to fix this. I tried increasing the heapsize for the JVM.

Related

my javafx project doesn't read data from the database

So i created a database table in intellij and i made a javafx project and it's connected to my server(localhost)
now i'm getting errors here
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
it says I'm unable to access the table
this is the method
public boolean isLogin(String user,String pass) throws SQLException
{
PreparedStatement preparedStatement = null ;
ResultSet resultSet = null;
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
try
{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,user);
preparedStatement.setString(2,pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
//TODO: handle exception
}
finally {
preparedStatement.close();
resultSet.close();
}
}
and the other error here
if (loginModel.isLogin(userAction.getText(), passAction.getText()))
and this line too
resultSet.close();
and I guess they are related and i don't know how to fix this
this is the other code
#FXML
public void Login(ActionEvent event) {
try {
if (loginModel.isLogin(userAction.getText(), passAction.getText())) {
isConnected.setText("Username & password is correct");
}
else
{
isConnected.setText("Check your username or password");
}
} catch (SQLException e)
{
isConnected.setText("Check your username or password");
//TODO Auto-generated catch block
e.printStackTrace();
}
}

ResultSet is getting closed on executing statement.execute(sql)

On executing the follwing code i am getting error java.sql.SQLException: ResultSet is closed
public class SavePoints {
public void extract(ResultSet rs)
{
int c;
try {
while(rs.next())
{
c = rs.getInt("id");
String d=rs.getString("name");
String e=rs.getString("city");
String f=rs.getString("state");
String g=rs.getString("country");
//Displaying values
System.out.println("ID is:"+c+"\tName is:"+d+"\tCity is:"+e+"\tState is:"+f+"\tCountry is:"+g);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
SavePoints spobj=new SavePoints();
try {
Connection con=DriverManager.getConnection("jdbc:odbc:Divya", "SYSTEM", "tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from publishers");
spobj.extract(rs);
//DatabaseMetaData databaseMetaData = con.getMetaData();
//System.out.println(databaseMetaData.getDriverMajorVersion());
//Savepoint sp=con.setSavepoint("Deleting Rows");
st.execute("delete from publishers where id=104");
//con.rollback(sp);
spobj.extract(rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What is the error? I cannot find it. Please let me know. I am a newbie.. so please explain in simple terms. I am grateful for your help. Thanks :)
you have called spobj.extract(rs); twice ,
first time when this function executes resultset moves to last because you are using rs.next()..
to achieve this you have use scrollable resultset
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
and for next call of spobj.extract(rs); reverse the call of resultset by rs.previous()

Issue : SQL Azure connection is broken . After reconnecting and accessing entity object , An Error occurred

Connected to website and keeping idle for 30 mins, then trying to access the entities I am getting the following error.
Entity framework An error occurred while executing the command definition. See the inner exception for details . Inner exception {“Invalid object name 'dbo.TableName'.”}
Sample Code
Static Class Azure
{
public static CrmEntities ConnectCustomerEntity()
{
CrmEntities customerEntity = null;
policy.ExecuteAction(() =>
{
try
{
var shardId = GetShardId();
customerEntity = new CrmEntities(ConnectionStringCustomerDB());
string federationCmdText = #"USE FEDERATION Customer_Federation(ShardId =" + shardId + ") WITH RESET, FILTERING=ON";
customerEntity.Connection.Open();
customerEntity.ExecuteStoreCommand(federationCmdText);
}
catch (Exception e)
{
customerEntity.Connection.Close();
SqlConnection.ClearAllPools();
//throw e;
}
});
return customerEntity;
}
public static CrmEntities DBConnect(CrmEntities _db)
{
try{
if (_db == null)
_db = Azure.ConnectCustomerEntity();
if ((_db.Connection.State == ConnectionState.Broken) || (_db.Connection.State == ConnectionState.Closed))
{
SqlConnection.ClearAllPools();
_db = Azure.ConnectCustomerEntity();
}
else
{ //This code is to find out any issues in connection pool database connection
string sqlCmdText = #"select top 1 Id from Project";
_db.ExecuteStoreCommand(sqlCmdText);
}
}
catch (Exception ex)
{
_db.Connection.Close();
SqlConnection.ClearAllPools();
_db = Azure.ConnectCustomerEntity();
}
return _db;
}
}
Mvc Controller. The following code I am gettting that exception, after 30 mins
public class FilterController : Controller
{
public ActionResult GetFilters(string entityName,string typeFilter)
{
_crmEntities=Azure.DBConnect(_db);
var query = _db.FilterFields.Where(filter => filter.TableId == tableId).ToList(); // Here I am getting that exception
}
}
I dont know, Why i m getting that exception. I tried all possibilities. Nothing helped. I really struck with this. If anybody knows please tell your views to come out from this exception
Thanks in Advance.
I think your session times out.
try to increase session timeout:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.timeout.aspx

Sql Notification Supported Isolation Levels for Transactions

I am running multiple inserts using transactions. I am using the SqlDependency class to let the client machine know when the server has been updated.
The problem I am having is that whenever I insert using a transaction, no matter what isolation level I set for the transaction, the SqlNotificationEventArgs returns e.Info as Isolation which indicates that I have the wrong isolation level set for that transactions (I think). When I insert without using a transaction, everything runs smoothly.
My questions is, what are the supported Isolation levels, if any, for transactions when using Sql Notification?
Below is some of the code I am using for the notification:
void DataChanged(object sender, SqlNotificationEventArgs e) {
var i = (ISynchronizeInvoke)_form;
if (i.InvokeRequired) {
var tempDelegate = new OnChangeEventHandler(DataChanged);
object[] args = { sender, e };
i.BeginInvoke(tempDelegate, args);
} else {
var dependency = (SqlDependency)sender;
if (e.Type == SqlNotificationType.Change) {
dependency.OnChange -= DataChanged;
GetData(dependency);
}
}
}
And for the transaction:
public void ExecuteNonQueryData(List<string> commandTexts) {
SqlConnection connection = null;
var command = new SqlCommand();
SqlTransaction transaction = null;
try {
connection = new SqlConnection(GetConnectionString());
connection.Open();
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
foreach (var commandText in commandTexts) {
try {
command.Connection = connection;
command.CommandText = commandText;
command.Transaction = transaction;
command.ExecuteNonQuery();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
transaction.Commit();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
} finally {
command.Dispose();
if (transaction != null) transaction.Dispose();
if (connection != null) {
connection.Close();
connection.Dispose();
}
}
commandTexts.Clear();
}
Edit: I was committing the transaction in the wrong place.
Apparently Query Notification does not support transactions. Removing the transaction code fixed this problem.
According to Microsoft:
Transact-SQL does not provide a way to subscribe to notifications. The CLR data access classes hosted within SQL Server do not support query notifications.
This quote was found at http://msdn.microsoft.com/en-us/library/ms188669.aspx, which describes how Query Notifications work and their requirements.

Liquibase does not commit my changes

I'm running Liquibase from a Java application to MSSQL with the JTDS driver. When I run the updates I see them displayed but nothing actually get's committed to the Database. Any ideas? The code below runs in a Servlet.
Connection con = null;
try {
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/datasource.properties"));
String driver = props.getProperty("database.driver");
String url = props.getProperty("database.url");
String username = props.getProperty("database.username");
String password = props.getProperty("database.password");
Class.forName(driver);
con = DriverManager.getConnection(url, username, password);
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(con));
Liquibase liquibase = new Liquibase("db.xml", new ClassLoaderResourceAccessor(), database);
response.getWriter().print("<PRE>");
liquibase.update("", response.getWriter());
con.commit();
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.warn(e.getMessage(), e);
}
}
}
response.flushBuffer();
The update() method that takes a writer will not execute changes, but rather output what would be ran.
If you call liquibase.update("") or liquibase.update(null) instead, it will execute the changes.