【问题标题】:Constraint failed UNIQUE constraint failed约束失败 UNIQUE 约束失败
【发布时间】:2016-03-24 12:19:18
【问题描述】:

我创建了几个连接到同一个数据库的程序。这段代码在某一时刻停止了异常工作:

约束失败 UNIQUE 约束失败:moz_cookies.name, moz_cookies.host、moz_cookies.path、moz_cookies.origin 属性。

接下来我该怎么做?

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;


namespace ReflCookie
{
    class CookieSQLite
    {
        protected SQLiteConnection SqLiteConnection;
        protected MyDBContext MyDbContext = new MyDBContext();

        public CookieSQLite()
        {
        }

        public CookieSQLite(string database)
        {
            SqLiteConnection = new SQLiteConnection(@"DataSource= "+database);
            try
            {
                SqLiteConnection.Open();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public List<CookieRow> GetCookie()
        {
            SQLiteCommand sqLiteCommand = new SQLiteCommand();
            sqLiteCommand.CommandText = "Select * from `moz_cookies` order by `id` asc";
            sqLiteCommand.Connection = SqLiteConnection;
             SQLiteDataReader sqLiteDataReader = sqLiteCommand.ExecuteReader();
                DataTable dataTable = new DataTable();
                List<CookieRow> cookies = new List<CookieRow>();
                dataTable.Load(sqLiteDataReader);
                foreach (DataRow row in dataTable.Rows)
                {
                    CookieRow cookie = new CookieRow();
                    cookie.Id = Convert.ToInt32(row.ItemArray[0].ToString());
                    cookie.BaseDomain = row.ItemArray[1].ToString();
                    cookie.OriginAttributes = row.ItemArray[2].ToString();
                    cookie.Name = row.ItemArray[3].ToString();
                    cookie.Value = row.ItemArray[4].ToString();
                    cookie.Host = row.ItemArray[5].ToString();
                    cookie.Path = row.ItemArray[6].ToString();
                    cookie.Expiry = row.ItemArray[7].ToString();
                    cookie.LastAccessed = row.ItemArray[8].ToString();
                    cookie.CreationTime = row.ItemArray[9].ToString();
                    cookie.IsSecure = Convert.ToInt32(row.ItemArray[10].ToString());
                    cookie.IsHttpOnly = Convert.ToInt32(row.ItemArray[11].ToString());
                    cookie.AppID = Convert.ToInt32(row.ItemArray[12].ToString());
                    cookie.InBrowserElement = Convert.ToInt32(row.ItemArray[13].ToString());

                    cookies.Add(cookie);
                }
                return cookies;
            }

        public void DeleteCookieRows()
        {
            SQLiteCommand sqLiteCommand = new SQLiteCommand();
            sqLiteCommand.CommandText= "DELETE FROM moz_cookies where Name = 'NID'";
            sqLiteCommand.Connection = SqLiteConnection;
            sqLiteCommand.Parameters.AddWithValue("Name", "NID");
            sqLiteCommand.ExecuteNonQuery();

        }

        public void IdCookieIsEmpty(List<CookieRow> c, List<CookieRow> cookiesRows, string profileCookies)
        {
            if (cookiesRows != null && cookiesRows.Count != 0)
            {
                UpdateCookie(c, profileCookies);
            }
            else
            {
                List<CookieRow> cookieRows = GetCookie();
                List<CookieRow> idCookies = cookieRows.Where(row => row.Name == "_gads").ToList();
                if (idCookies != null && idCookies.Count != 0)
                {                   
                    foreach (CookieRow cookie in idCookies)
                    {
                        MyDbContext.Cookie.Add(cookie);
                    }
                    MyDbContext.SaveChanges();
                    Console.WriteLine("Cookies saved to 'AMAZONE_db' file");
                    Console.WriteLine("Press any key to close application");
                }
                List<CookieRow> qLiteCookie = MyDbContext.Cookie.ToList();
                UpdateCookie(qLiteCookie, profileCookies);

            }

        }

        private void UpdateCookie(List<CookieRow> c, string profileCookies)
        {
            foreach (CookieRow cookie in c)
            {
                SQLiteCommand sqLiteCommand = new SQLiteCommand();
                SQLiteConnection qLiteConnection = new SQLiteConnection(@"DataSource= " + profileCookies);
                qLiteConnection.Open();
                sqLiteCommand.CommandText =
                    "UPDATE moz_cookies SET  Id='"+cookie.Id+"',BaseDomain = '" + cookie.BaseDomain + "', " +
                    "originAttributes='" + cookie.OriginAttributes + "'," +
                    "name='" + cookie.Name + "', value='" + cookie.Value + "', " +
                    "host='" + cookie.Host + "',path='" + cookie.Path + "', " +
                    "expiry='" + cookie.Expiry + "', lastAccessed='" + cookie.LastAccessed + "', " +
                    "creationTime='" + cookie.CreationTime + "', isSecure='" + cookie.IsSecure + "', " +
                    "isHttpOnly='" + cookie.IsHttpOnly + "', appId='" + cookie.AppID + "', " +
                    "inBrowserElement='" + cookie.InBrowserElement + "'";

                sqLiteCommand.Connection = SqLiteConnection;
                sqLiteCommand.ExecuteNonQuery();

                qLiteConnection.Close();

                Console.WriteLine("D");
            }
        }
    }
}

【问题讨论】:

  • 显然,您需要找出违反唯一约束的原因。由于您尚未发布您的架构,我只能假设这些字段存在 UNIQUE,并且当您在这些列中插入相同的数据时,它在逻辑上会失败。
  • 接下来您应该阅读SQL Injection 并使用参数化查询。之后,找出你想如何处理已经在你的数据库中的 cookie 记录。

标签: c# sql sqlite


【解决方案1】:

您收到的错误消息实际上是在告诉您出了什么问题:您的表中已经存在一条记录,其中 moz_cookies.namemoz_cookies.hostmoz_cookies.pathmoz_cookies.origin 的值相同,并且有一个约束阻止添加新的。

您希望如何处理这取决于您。

另外,我建议您阅读 SQL Injection,因为您的代码非常容易受到它的攻击。

【讨论】:

    猜你喜欢
    • 2018-11-17
    • 2021-12-09
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多