using JiangSu.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Reflection;
using System.Web;
namespace JiangSu.cs
{
public class ModelDAL
{
///
/// 获取参数列表
///
public static SQLiteParameter[] GetParams(string sql, T t)
{
List list = new List();
Type tType = typeof(T);
BindingFlags flags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
int start = sql.IndexOf("@");
while (start != -1)
{
int end = sql.IndexOf(",", start);
if (end == -1) end = sql.IndexOf(")", start);
if (end == -1) end = sql.IndexOf(" ", start);
if (end == -1) end = sql.Length;
string name = sql.Substring(start + 1, end - start - 1);
PropertyInfo pi = tType.GetProperty(name, flags);
if (pi != null)
{
object value = pi.GetValue(t, null);
SQLiteParameter dp = new SQLiteParameter("@" + name, value);
list.Add(dp);
}
start = sql.IndexOf("@", end);
}
return list.ToArray();
}
public static Model SelectById(long id)
{
string sql = "select * from model where id = @id";
SQLiteParameter param = new SQLiteParameter("@id");
param.Value = id;
DataTable dt = SQLiteHelper.GetDataTable(sql, param);
if (null == dt || dt.Rows.Count == 0)
{
return null;
}
List list = ModelHandler.FillModel(dt);
return null == list || list.Count == 0 ? null : list[0];
}
public static int DeleteByIds(List list)
{
string ids = string.Join(",", list.ToArray());
string sql = string.Format("delete from model where id in ({0})", ids);
return SQLiteHelper.ExecuteNonQuery(sql);
}
public static int insert(Model model)
{
string sql = "insert into model (name, json) values (@name, @json)";
SQLiteParameter[] sqlParams = GetParams(sql, model);
return SQLiteHelper.ExecuteNonQuery(sql, sqlParams);
}
public static int UpdateById(Model model)
{
string sql = "update model set name = @name, json = @json where id = @id";
SQLiteParameter[] sqlParams = GetParams(sql, model);
return SQLiteHelper.ExecuteNonQuery(sql, sqlParams);
}
}
}