I have a C# winforms application with SQLite as database which have a few tables.
The application has a datagridview
control that represents data from database.
I want a user to be able to change database table fields, which is easy by using SQL `ALTER query.
The problem comes when the user wants to insert some data to the database table because I need to know the table's field name in order to construct a valid INSERT
query.
I usually just hard-coded field names, because I never had an option that allows user to change the table's field name in a database.
My idea is that my INSERT
query uses datagridview
's column names, so, when a user changes the table's field name, it also changes the grid's field names, and every time the application runs, grid's columns are named to the names same as database table has.
That way I always have an access to the right field name.
Or can I just use an index instead of string to reference a field?
Usually I use this code to insert data.
class SQLiteDatabase
{
//...
public bool Insert(String tableName, Dictionary<String, String> data)
{
String columns = "";
String values = "";
Boolean returnCode = true;
foreach (KeyValuePair<String, String> val in data)
{
columns += String.Format(" {0},", val.Key.ToString());
values += String.Format(" '{0}',", val.Value);
}
columns = columns.Substring(0, columns.Length - 1);
values = values.Substring(0, values.Length - 1);
try
{
this.ExecuteNonQuery(String.Format("insert into {0}({1}) values({2});", tableName, columns, values));
}
catch(Exception fail)
{
MessageBox.Show(fail.Message);
returnCode = false;
}
return returnCode;
}
//...
}
db = new SQLiteDatabase();
Dictionary<String, String> myData = new Dictionary<String, String>();
myData.Add("NAME", "something");
myData.Add("LAST_NAME", "something");
try
{
db.Insert("TABLE_NAME", myData);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Edit: I just read that in SQLite it is not possible to rename a column, remove a column, or add or remove constraints from a table.... WTF? This is the solution to rename columns...