SQLiteHelper封装类
public class SQLiteHelper { private static readonly string conStr = ConfigurationManager.AppSettings["SQLiteDbConn"].ToString() /// <summary> ///增、删、改 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="pms">SQL参数</param> /// <returns>受影响的行数</returns> public static int Execute(string sql, params SQLiteParameter[] pms) { using (SQLiteConnection conn = new SQLiteConnection(conStr)) { using (SQLiteCommand cmd = new SQLiteCommand(sql, conn)) { if (pms != null) { cmd.Parameters.AddRange(pms); } try { conn.Open(); } catch { throw; } return cmd.ExecuteNonQuery(); } } } /// <summary> /// 查询单个结果,一般和聚合函数 一起使用 /// </summary> /// <param name="sql">查询的SQL语句</param> /// <param name="pms">SQL参数</param> /// <returns>返回查询对象,查询结果第一行第一列</returns> public static object ExecuteScalar(string sql, params SQLiteParameter[] pms) { using (SQLiteConnection conn = new SQLiteConnection(conStr)) { using (SQLiteCommand cmd = new SQLiteCommand(sql, conn)) { if (pms != null) { cmd.Parameters.AddRange(pms); } try { conn.Open(); } catch { throw; } return cmd.ExecuteScalar(); } } } /// <summary> /// 查询多行 /// </summary> /// <param name="sql">SQL语句</param> /// <param name="pms">SQL参数</param> /// <returns>返回SqlDataReader对象</returns> public static SQLiteDataReader ExcuteReader(string sql, params SQLiteParameter[] pms) { SQLiteConnection sqliteConn = new SQLiteConnection(conStr); SQLiteCommand cmd = new SQLiteCommand{ Connection = sqliteConn, CommandText = sql }; if (pms != null) cmd.Parameters.AddRange(pms); if (sqliteConn.State != ConnectionState.Open) sqliteConn.Open(); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } }
查询数据:
public object GetList() { List<UserLog> Logs = new List<UserLog>(); string sqlStr = @"select Name from UserLog order by CareteTime desc limit 1"; return SQLiteHelper.ExecuteScalar(sqlStr, null); }
public List<User> GetAll() { List<User> userlist = new List<User>(); string sqlStr = @"select Gid,Phone,Name"; SQLiteDataReader reader =SQLiteHelper.ExcuteReader(sqlStr, null); while (reader.Read()) { User item = new User(); item.Gid = Guid.Parse(reader[0].ToString()); item.Phone = reader[1].ToString(); item.Name = reader[2].ToString(); userlist.Add(item); } reader.Close(); return userlist; }
保存数据
public bool Save(user User) { string sqlStr = @"insert into User(Gid,Phone,Name) values (@Gid,@Phone,@Name)"; SQLiteParameter[] parameters = { new SQLiteParameter("@Gid", user.Gid), new SQLiteParameter("@Phone", user.Phone), new SQLiteParameter("@Name", user.Name), }; return SQLiteHelper.Execute(sqlStr, parameters) > 0; }