Add a Class to SQLite Database

Those days I am programming to store settings in sqlite database. I am define every setting to a class, But it is not easy to write every funciton to add every new setting to database.So I use generics type to do it.

private int AddNewItem<T>(string table, T t)
{
    StringBuilder sb = new StringBuilder("insert into ");
    sb.Append(table);
    sb.Append(" values (");

    PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
    List paramlist = new List(properties.Length);
    foreach (PropertyInfo property in properties)
    {
        sb.Append("@");
        sb.Append(property.Name);
        sb.Append(",");
        paramlist.Add(new SQLiteParameter("@" + property.Name, property.GetValue(t, null)));
    }
    sb.Length -= 1;//remove last ","
    sb.Append(")");

    paramlist[0].Value = null;//it must be "id" colume
    return SQLiteHelper.ExecuteIns(sb.ToString(), paramlist.ToArray());
}

 

For example,the table is created by sql

"CREATE TABLE IF NOT EXISTS [settings]( id INTEGER PRIMARY KEY AUTOINCREMENT,key TEXT,value TEXT);"

And the class is defined as

class SettingItem
{
    public long id { get; set; }
    public string key {get;set;}
    public string value { get; set; }
}

Just add a new key-value pair by calling

private int AddNewKeyValue(SettingItem item)
{
    return AddNewItem<SettingItem>("[settings]", item);
}
Share

Related posts:

  1. How to Reflect DataRow to Modal
This entry was posted in IT. Bookmark the permalink.

One Response to Add a Class to SQLite Database

  1. Вы всегда публикуете только лучшую информацию. У вас просто супер блог. Спасибо

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>