Can't rename SQLite database file after using it - sqlite

I'm trying to rename my SQLite database file after I'm done using it, however the file still appears to be opened by SQLite even after all my connections are closed.
Here is an example of what I'm doing:
using (DbConnection conn = new SQLiteConnection("Data Source=test.db"))
{
conn.Open();
DbCommand command = conn.CreateCommand();
command.CommandText = "select id from test";
command.ExecuteScalar();
}
File.Move("test.db", "test.db.test");
The Move call throws an IOException. This is the only connection that I have to this database file. Once the application ends I can move the file manually without a problem. I've tried various things such as explicitly setting Pooling=false in the connection string, manually calling Close before the connection is disposed, explicitly starting and committing a transaction, but none of this seems to help. Is there a way to force SQLite to close/release the database file without exiting the application?

I presume you are using SQLite.Net? I have just tried your code and works without problem with SQLite.Net 1.0.65, in VS 2005 on Vista.

DBCommand is IDisposable. Maybe you need to call Dispose on it or create it in a using statement.

Related

Can you insert a new database connection in an existing database connection in OLEDB?

I am creating a program in which I am trying to have a new database connection in an existing database connection in OLEDB using ASP.net. Is that even possible?
"Connection within connection" is likely not what you have in mind. But there is no issue with having both OleDb and SQLServer connections operating together in one ASP.NET application, you can add these 2 or many more connections to one app.
Answer is yes. Please make sure you close the connections after using by using statement or close() explicitly. More here.
using (OleDbConnection connection1 = new OleDbConnection(connectionString1))
using (OleDbConnection connection2 = new OleDbConnection(connectionString2))
{
connection1.Open();
connection2.Open();
// Do something
}

oracle ExecuteNonQuery freezes on ASP.Net

I am trying to run a non query using a Oracle connection in ASP C# with CLR 4.5. Here is my code:
string connectionString = ConfigurationManager.ConnectionStrings["OracleConnectionString1"].ConnectionString;
OracleConnection conn = new OracleConnection(connectionString);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "update SALES_ADVENTUREWORKS2012.SALESORDERDETAIL set UNITPRICEDISCOUNT=0 where ROWGUID='4A399178-C0A0-447E-9973-6AB903B4AECD'";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = QUERY_TIMEOUT;
int row_affected = cmd.ExecuteNonQuery();
HttpContext.Current.Response.Write("Rows affected:" + row_affected + "<br/>");
conn.Close();
when I run the query in oracle development tool, it works fine.
when I use the asp code above, it freezes when performing the query. It freezes forever even though I used a 5 second timeout.
I've tried using the managed and unmanaged oracle libraries; both behave the same.
Note that using the fill or scalar query work perfectly fine so there is nothing wrong with my connection string. Also the fact that oracle development can perform this update query proves that this is not a permission problem.
Any ideas?
Most likely your query is waiting to get access to the record. You probably have modified that row in "oracle development tool" and have not committed or rolled back that transaction.
Just commit/rollback in your tool or close open session.
You can check for open transactions in v$transaction view.
More on automatic locks in Oracle:
http://docs.oracle.com/cd/E11882_01/server.112/e41084/ap_locks001.htm
Are you certain you are using the 4.5 library? The 3.5 documentation states that the CommandTimeout property has no effect.
The 4.5 documentation suggests it should work, but the Remarks section doesn't mention the change, which warrants suspicion.
Otherwise, the code you posted doesn't seem to show where you actually set the value of QUERY_TIMEOUT to 5 seconds. If QUERY_TIMEOUT has a value of zero, then any other provider (SQLCommand, for example) would wait indefinitely. As vav suggested, locks from other sources could cause an indefinite wait.

SQL Connection Forcibly Closed

I'm having difficulty with an SQL query against Server 2008 from IIS7. I have a VB.NET class library which runs an update statement. The underlying code used to create the connection hasn't changed, but suddenly the query is failing in our testing and development environments. It does, however, still work against the same server/database using the slightly older code in our production environment.
I've tried setting the connection timeout in the web.config and I'm at a loss to explain the cause.
The basic structure of the query is:
Dim conn = New SqlConnection()
conn.ConnectionString = "Data Source=someserver\sqlexpress2008;Initial Catalog=DatabaseName;User ID=sa;Password=pass"
conn.Open()
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "UPDATE ..."
cmd.Parameters.AddWithValue("#UName", user.name)
cmd.ExecuteNonQuery() 'fails with error
End Using
The error is:
A transport-level error has occurred when sending the request to the
server. (provider: TCP Provider, error: 0 - An existing connection was
forcibly closed by the remote host.)
I've tried restarting IIS and the SQL server and I'm totally out of ideas. I just need a fix
You need to open the connection before calling SqlCommand.ExecuteNonQuery(). You do this by calling SqlConnection.Open().
Dim conn = New SqlConnection()
conn.ConnectionString = "Data Source=someserver\sqlexpress2008;Initial Catalog=DatabaseName;User ID=sa;Password=pass"
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "UPDATE ..."
cmd.Parameters.AddWithValue("#UName", user.name)
conn.Open()
cmd.ExecuteNonQuery() 'fails with error
conn.Close()
End Using
Also, ensure you database isn't in single user mode.
This helped another person who was stuck recently. You could examine the problem from the database server by setting up a SQL Server Profiler.
You can find lots of info about SQL Profiler by just googling around. Here's a site with a video that might help you get started. For starters, you would be able to see if the request is even reaching the database server.
This was a nightmare to track down. It turned out to be cause by a horrible quirk in VB.NET. Nullable datetimes seem to be coerced to DateTime.MinValue, which resulted in a DateTime.MinValue being inserted into an sql datetime. The fix was to check for either !property.HasValue && property.Value != DateTime.MinValue when setting the parameters for the command.
This is a network-level error. The database server is killing the connection for some reason. In order to troubleshoot this, I would open a connection using SSMS to the DEV and TEST servers and make sure that I can run simple queries w/o problems. It's unlikely that the issue is your library since you would be getting timeout or some other kind of errors.
as Lcarus, said, database server is killing the connection for unknown reason.
you can check the logs, to verfiy. Log path will be C:\Program Files\Microsoft SQL Server\<your instance>\MSSQL\LOG
from MSDN Blog MSDN Blog
this will occur when A connection is taken from the connection pool,
the application does not know that the physical connection is gone, an
attempt to use it is done under the assumption that the physical
connection is still there.

Closing database connection in asp.net

Can we close all known/unknown connections to database with the code?
I'm using Access database and my application gives the following error:
"Could not use ''; file already in use. "
I don't know which connection is opened and no closed, so is there a way to close all application's opened connections?
When working with disposable objects you should use using so they will get disposed, and in this case even closed, when leaving the using block. Your code should look something like:
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
Read about OleDbConnection.
UPDATE: I missed that you were accessing an access database, so updated the code to use OleDbConnection instead.

Best way to establish a connection for use with an ADO.NET command object

I'm designing a web service in ASP.NET and VS2008, and am using typed datasets for retrieving table data. These work well and establish their own connections through their associated TableAdapter objects. Edit: I'm using VB, BTW!
I am now attempting to run a custom SQL string using a DataAdapter and a Command object, however I need to reference a Connection object in order for the Command to work. What is the best way to handle this? Should I:
a) Create a global connection object using Global.asax, retrieving the connection string from web.config? (I've been trying that one already, with not much success)
b) Create a class-level connection object using the InitialiseComponent method, also retrieving the ConnectionString from web.config?
c) Retrieve a Connection from one of the TableAdapters that I've already created in my typed DataSets?
d) Something else I haven't thought of yet?
BTW I've been finding it very difficult to extract a ConnectionString from web.config, so any help with that would be appreciated also!
I'm not entirely inexperienced with ASP.NET, but my last big project used VS2003, and I want to make sure that I'm using the current tools correctly.
To extract the connection string, use
WebConfigurationManager.ConnectionStrings["name"].ConnectionString
It's best to open and close the connections as close as possible to their use. ADO.NET will do connection pooling so that this won't be expensive:
var connectionString =
WebConfigurationManager.ConnectionStrings["name"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("query", conn))
{
conn.Open();
// Use the command
}
}
For Connection and data access problems I will advise you to go with some kind of Data Helpers like Microsoft Data Access Application Block
Here you can find small tutorial about how to use it.
For getting connectionstring from web.config use folowing methods
public static string GetConnectionString( string strConstringKey )
{
return ConfigurationManager.ConnectionStrings[strConstringKey];
}
public static bool GetConnectionString(string strConstringKey, ref string strConstring)
{
return (strConstring = ConfigurationManager.ConnectionStrings[strConstringKey] ) == null ? false : true ;
}

Resources