SQLite执行多个参数(SQLiteParameter)

2020-02-18 更新
Web.config文件里面代码
  <appSettings>
    <!--数据库绝对地址,默认为Path-->
    <add key="Path" value="/SQLite/DataDB.db"/>
  </appSettings>


      /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public static SQLiteConnection GetSQLiteConnection(string dbName = "")
        {
            try
            {
                //如果配置里面读取不到则直接构建链接字符串
                string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings[dbName + "Path"].ToString());
                string connStr = string.Format("Data Source={0};Pooling=True", path);
                if (string.IsNullOrEmpty(connStr))
                {
                    connStr = @"Data Source=" + dbName;
                }

                return new SQLiteConnection(connStr);
            }
            catch
            {
                return null;
            }
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public static void Add(Model.UserinfoModel model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into UserInfo(");
            strSql.Append("OSVersion,Browser,IPAddress,upDateTime)");
            strSql.Append(" values (");
            strSql.Append("@OSVersion,@Browser,@IPAddress,@upDateTime)");
            SQLiteParameter[] parameters = {
                    new SQLiteParameter("@OSVersion", model.OSVersion),
                    new SQLiteParameter("@Browser", model.Browser),
                    new SQLiteParameter("@IPAddress", model.IPAddress),
                    new SQLiteParameter("@upDateTime", model.upDate)};
            ExecuteSql(strSql.ToString(), parameters);
        }


        public static int ExecuteSql(string SQLString, params SQLiteParameter[] p)
        {
            using (SQLiteConnection connection = GetSQLiteConnection())
            {
                SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
                    cmd.Parameters.AddRange(p);
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (Exception ex)
                    {
                        return 0;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }


评论