最近刚开始学习C#,大家不断指教 我才能不断进步
public void Add<T>(IList<T> collection, SQLiteConnection conn)
{
Type type = typeof(T);
PropertyInfo[] propertes = type.GetProperties();
string className = type.FullName.Split('.')[type.FullName.Split('.').Length-1].ToUpper();
StringBuilder sb = new StringBuilder();
sb.Append("insert into TB_").Append(className).Append("(");
for (int i = 0; i < propertes.Length; i++)
{
if (i > 0)
{
sb.Append(",");
}
sb.Append(propertes[i].Name);
}
sb.Append(") values (");
for (int i = 0; i < propertes.Length; i++)
{
if(i > 0)
{
sb.Append(",");
}
sb.Append("@" + propertes[i].Name);
}
sb.Append(")");
SQLiteCommand cmd = conn.CreateCommand();
cmd.CommandText = sb.ToString();
using(SQLiteTransaction transaction = conn.BeginTransaction())
{
foreach (T c in collection)
{
foreach (PropertyInfo info in propertes)
{
cmd.Parameters.AddWithValue("@" + info.Name, info.GetValue(c, null));
}
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
transaction.Commit();
}
}