This question already has answers here:
SQLite Concurrent Access
(8 answers)
Closed 8 years ago.
I'm developing an app with C# and SQLite. My problem is, I need to execute INSERT query and SELECT query at the same time. If I explain with more detail my problem is;
Let's say my database name is myDB,
I'm importing a 1 MB text file to myDB. While this import is processing, is another window (in the same app and using same connection and same database file) can execute a SELECT query?
Thank you for helping!
Ok, why you need select? you will get something of the insert and put in another table? Or the program need keep run like nothing are running?
if you need select to put in another table, you can use it:
select * from table order by cod desc limit 1;
or, if you need keep running, you will need a thread, its a example:
onLoad()
{
Thread t = new Thread(new ThreadStart(t_trigger));
t.Start();
}
private void t_trigger()
{
table_insert(string d)
}
private delegate void delegate_table_insert(string d);
private void table_insert(string d)
{
if (InvokeRequired)
{
try
{
Invoke(new delegate_table_insert(table_insert), d);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
else
{
try
{
// here run the code
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
Related
I have web form which has a button.When you click that button,it will create a text file and write something to it.Just imagine like i am writing large things of 1G content ,which will change once in a day.And this is an asp.net application and many users will use.So suppose first user clicks at morning 6.o clock it will generate .Now i want to resuse it for others rather creating a new one till next morning 6 o clock.How to do it.I am posting a small prototype code
try
{
File.WriteAllText("E:\\test.txt", "welcome");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
NB:This is an asp.net application so cant think of thread.So i am not thinking
While(true)
{
Thread.Sleep() etc
}
Use File.GetLastWriteTime Method to check last modification in file
try
{
if(!File.Exists("E:\\test.txt") )
{
File.WriteAllText("E:\\test.txt", "welcome");
}
else
{
if(File.GetLastWriteTime(path).Day != DateTime.Now.Day)
{
//code for next day
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Assuming you are making a new file every day, and already have delete logic in place at the end of the day.
Check and see if the file exists before you create it.
try
{
if (//file does not exist)
File.WriteAllText("E:\\test.txt", "welcome");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
You could also check on the date of the file and if outside of your parameters then delete and create a new one (in the same if condition as the 'exists' logic).
Perhaps you should try using an Application variable to store the last time the file has been written ( a date value ) and just be sure that the file is only ever written once per day. For example:
Dim dt as DateTime
If TryCast(Application("LastFileWrite"), dt) Then
If String.Compare(dt.Date.ToString(), Now.Date.ToString()) <> 0 Then
' we're a different day today, go ahead and write file here
End If
Else
' we've never writting this application variable, this is
' the first run, go ahead and write file here as well
End If
For more information about the Application state, take a look at the following documentation:
https://msdn.microsoft.com/en-us/library/bf9xhdz4(v=vs.71).aspx
This should prevent two or more threads from writing the same file twice.
The first thread to grab the lock will create the file, then the other threads will skip creating the file with the second check of the file inside the lock.
public static object fileLock = new object();
public void createFile()
{
if (File.Exists("filepath") == false) {
lock (fileLock) {
if (File.Exists("filepath") == false) {
File.WriteAllText("E:\\test.txt", "welcome");
}
}
}
}
I made a code that create a Database in .sqlite, all working good but I want to be sure that when the user start for the first time the application the Database population must be completed. If the user abort the database population, the database must be deleted (because the application don't working with an incomplete resource). Now I've used the thread for execute the method that create this Database, and I've declared the thread variable global in the class, like:
Thread t = new Thread(() => Database.createDB());
The Database.createDB() method create the DB. All working perfect, the DB is created correctly. Now I fire the closing of the window that creating the DB like:
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult result = MessageBox.Show(
#"Sure?",
"Attention", MessageBoxButton.YesNo, MessageBoxImage.Question);
try
{
if (result == MessageBoxResult.Yes)
{
t.Abort();
if (File.Exists("Database.sqlite"))
{
File.Delete("SoccerForecast.sqlite");
Process.GetCurrentProcess().Kill();
} ....
The event was fired correct and the thread stopped, but when the condition start if (File.Exists("Database.sqlite")) the compiler tell me:
Can't delete file - in using by another process.
But I've stopped the thread, why this exception appear? What I doing wrong?
UPDATE:
In CreateDb() method I also have a call to other method of different class, one of this have the structure like this:
public void setSoccer()
{
Database.m_dbConnection.Open();
string requestUrl = "...";
string responseText = Parser.Request(requestUrl);
List<SoccerSeason.RootObject> obj = JsonConvert.DeserializeObject<List<SoccerSeason.RootObject>>(responseText);
foreach (var championships in obj)
{
string sql = "string content";
SQLiteCommand command = new SQLiteCommand(sql, Database.m_dbConnection);
try
{
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
string query = "select * from SoccerSeason";
SQLiteCommand input = new SQLiteCommand(query, Database.m_dbConnection);
SQLiteDataReader reader = input.ExecuteReader();
int i = 0;
while (reader.Read())
{
//reading data previously inserted in the database
}
Database.m_dbConnection.Close(); /
}
I was wondering where I should put the flag variable because this code have a different loop inside.
It could be that when you're aborting the thread it's not cleanly closing the database connections, hence the error you're seeing.
Might I suggest a slight redesign because using Thread.Abort is not ideal.
Instead use a variable as a cancel flag to notify the thread to shut down.
Then when the thread detects that this cancel flag is set it can properly close connections and handle the database delete itself.
Update:
A brief example to illustrate what I mean; it ain't pretty and it won't compile but it gives the general idea.
public class Database
{
public volatile bool Stop= false;
public void CreateDb()
{
if(!Stop)
{
// Create database
}
if(!Stop)
{
// Open database
// Do stuff with database
}
// blah blah ...
if(Stop)
{
// Close your connections
// Delete your database
}
}
}
...
protected override void OnClosing(CancelEventArgs e)
{
Database.Stop = true;
}
And now that you know roughly what you're looking for I heartily recommend Googling for posts on thread cancellation by people who know what they're talking about that can tell you how to do it right.
These might be reasonable starting points:
How to: Create and Terminate Threads
.NET 4.0+ actually has a CancellationToken object with this very purpose in mind Cancellation in Managed Threads
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public Boolean Delete(Int32 HolidayNo)
{
//provides the functionality for the delete class
//create an instance of the data connection class called MyDatabase
clsDataConnection MyDatabase = new clsDataConnection();
//add the HolidayNo parameter passed to this function to the list of parameters to use in the database
MyDatabase.AddParameter("#HolidayNo", HolidayNo);
//execute the stored procedure in the database
MyDatabase.Execute("sproc_tblHolidays_Delete");
//return value for function
return true;
}
catch
{
return false;
}
}
The catch is saying invalid token. No idea how to fix...
For those curious, I'm making a delete function to delete certain values in my database for University.
Change your code to add a try and then check the exception details for any inner exceptions.
public Boolean Delete(Int32 HolidayNo)
{
try
{
//provides the functionality for the delete class
//create an instance of the data connection class called MyDatabase
clsDataConnection MyDatabase = new clsDataConnection();
//add the HolidayNo parameter passed to this function to the list of parameters to use in the database
MyDatabase.AddParameter("#HolidayNo", HolidayNo);
//execute the stored procedure in the database
MyDatabase.Execute("sproc_tblHolidays_Delete");
//return value for function
return true;
}
catch (Exception ex)
{
return false;
}
}
The reason you're getting an Unexpected Token error is that your catch block is completely outside of your method. Also, you're missing the try portion of the try / catch. To correct this, put the catch block inside your method and put the rest of your code in a try block just before the catch:
public Boolean Delete(Int32 HolidayNo)
{
try
{
clsDataConnection MyDatabase = new clsDataConnection();
MyDatabase.AddParameter("#HolidayNo", HolidayNo);
MyDatabase.Execute("sproc_tblHolidays_Delete");
return true;
}
catch
{
return false;
}
}
I don't even know how that compiled. Please begin by cleaning up your method. Like so:
public Boolean Delete(Int32 HolidayNo)
{
var deleted = false;
try {
if (HolidayNo > 0) {
//provides the functionality for the delete class
//create an instance of the data connection class called MyDatabase
clsDataConnection MyDatabase = new clsDataConnection();
//add the HolidayNo parameter passed to this function to the list of parameters to use in the database
MyDatabase.AddParameter("#HolidayNo", HolidayNo);
//execute the stored procedure in the database
MyDatabase.Execute("sproc_tblHolidays_Delete");
deleted = true;
}
}
catch (Exception ex)
{
// TODO: Log exception ex
return deleted;
}
}
This question already has answers here:
Keep an Application Running even if an unhandled Exception occurs
(5 answers)
Closed 8 years ago.
I have an application that connect with two server. If it cannot connect with a server, an exception is thrown. I want the program to continue executing and instead try to connect to the other server. How can I do that?
Use a try catch block.
var serversToTry = new []{"Server1", "Server2"};
foreach (var server in serversToTry)
{
try{
//connect to server
return; //if you made it this far, connection succedded.
}
catch (Exception e)
{
//log e if you want
}
}
Just use the go to function try-catch:
try
{
//do something
}
catch(SpecificException ex)
{
}
catch(LessspecificException ex)
{
}
catch(EvenLessSpecificException ex)
{
}
catch(Exception ex)
{
//general exception
}
finally
{
//execute always!
}
Note, that you can use multiple catch statements to catch different exceptions. Use the most specific exceptions first and generalize from there on.
the finally statement is optional, but if you implement it, it will get called everytime, no matter if an exception occured or not.
This question already has answers here:
Will code in a Finally statement fire if I return a value in a Try block?
(12 answers)
Does the C# "finally" block ALWAYS execute? [duplicate]
(11 answers)
Closed 9 years ago.
Please note this code:
class CTestFinally
{
public static void Run()
{
try
{
TryAndTry();
}
catch (Exception exError)
{
Console.WriteLine(exError.Message);
}
finally
{
Console.WriteLine("Finally...!");
}
Console.ReadKey();
}
static void TryAndTry()
{
try
{
TryAndTry();
}
catch (Exception exError)
{
Console.WriteLine(exError.Message);
}
finally
{
Console.WriteLine("Try: Finally...!");
}
}
}
}
Finally never executed because we get stack overflow Error.
Are there any circumstances under which the finally block does not get executed other than
above problem?
StackOverflowException is one of the few kinds of exception that a CLR host typically treats specially. ASP.NET will kill the worker process for example. This is very hard to debug because your app just goes away. SQL Server has similar policies I'm sure (like unloading the appdomain).
The reason for that is that this is a destabilizing condition that does not allow for reliable error recovery (after all your stack is unusable! You can for example not call your logger or send an email. There is no room on the stack.).
Another of this kind is OutOfMemoryException (you can't even allocate an Exception - that's why the CLR pre-allocates one OOM instance...). I think ASP.NET tolerates this while SQL Server kills your appdomain.
For normal exceptions this works fine.
This will never execute the finally:
using System;
namespace Demo
{
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
try
{
Console.WriteLine("In try");
Environment.FailFast("Aaaaaargh");
}
finally
{
Console.WriteLine("In finally");
}
}
}
}