The following function is used for the newer version of my app which needs to add a column to the existing database.
public void AddColumnIfNotexist()
{
try
{
using (SQLiteCommand cmd = _DBConnection.CreateCommand())
{
cmd.CommandText = string.Format("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'myTable'");
bool hascol = false;
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
//does column exists?
hascol = reader.GetString(0).Contains(String.Format("\"{0}\"", "myNewColumn"));
reader.Close();
}
}
if (!hascol)
{
StringBuilder sql = new StringBuilder(SQLMAXLENGTH);
sql.Append("ALTER TABLE Groups ADD COLUMN IsStayingRatio BIT NOT NULL DEFAULT 0");
cmd.CommandText = sql.ToString();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\r\n\r\n" + ex.StackTrace);
LogApp.Write("Exception ex:" + ex.Message +"stacktrace "+ex.StackTrace, LogApp.Level.Error);
}
}
}
When I execute this gets an exception as
database is locked
Stacktrace
at System.Data.SQLite.SQLite3.Step(SQLiteStatement stmt)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
at DataPlus.DB.AddColumnIfNotexist() in D:\Projects\DB.cs:line 343
But this is not always happened. this happens if the size of the DB Fil is large. Also, the issue is not there while debugging from the IDE.
Is there any limitations for the Alter Table query? Can anyone spot out the issue which makes the DB locked?