猿问

c# android中是否存在记录如何检查Sqlite

我有 c# android 应用程序。我有一个表单,其中包含一些字段 jobno、路线、成本,当用户填写表单并按保存时,信息将存储在应用程序的 SQLite 数据库中。


我想做的是在 if 检查记录是否存在时添加一个 if 语句;如果没有添加条目,则不添加记录。


这是用户单击保存按钮时的代码。


    Record photo = new Record()

    {

        Jobno = jobno.Text,

        route= route.Text,

        cost= cost.Text,

        Timestamp = timestamp.Timestamp,


    };




    using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))

    {


        //check if records exist



        conn.CreateTable<Record>();

        var numberofrows = conn.Insert(record);


        if (numberofrows > 0)

        {

            DisplayAlert("Success", "record has been saved successfully", "Ok");

            MainImage.Source = " ";

        }

        else

        {

            DisplayAlert("Failure", "Error occoured while saving record", "Try again");

        }

    }

如何添加 if 语句以仅在不存在时添加新记录。


提前致谢


编辑问题

    using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.DB_PATH))

    {


        //check if records exist



        conn.CreateTable<Record>();

        var items = conn.Table<Record>().Where(array => array.Jobno == photo.Jobno && array.Applicationletter == photo.Applicationletter && array.Signno == photo.Signno);


        if (items == null)

        {

            var numberofrows = conn.Insert(photo);


            if (numberofrows > 0)

            {

                DisplayAlert("Success", "record has been saved successfully", "Ok");

                MainImage.Source = " ";

            }

            else

            {

                DisplayAlert("Failure", "Error occoured while saving record", "Try again");

            }

        }

        else

        {

            DisplayAlert("Failure", "Photo already exist", "ok");

        }


        //clear the notes field

        notesentry.Text = "";

    }


守着一只汪
浏览 145回答 1
1回答

郎朗坤

试试这个方法。我不确定你的 sqlite 代码是如何工作的,所以我只是在这里猜测。我还猜测您想检查新创建的记录是否存在,因此此代码基于此。conn.CreateTable<Record>();//check if records existvar items = conn.Table<Record>().Where(array => array.Jobno == photo.Jobno && array.Applicationletter == photo.Applicationletter && array.Signno == photo.Signno);if (items?.Count() == 0){&nbsp; &nbsp;var numberofrows = conn.Insert(record);&nbsp; &nbsp;if (numberofrows > 0)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; DisplayAlert("Success", "record has been saved successfully", "Ok");&nbsp; &nbsp; &nbsp; MainImage.Source = " ";&nbsp; &nbsp;}&nbsp; &nbsp;else&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; DisplayAlert("Failure", "Error occoured while saving record", "Try again");&nbsp; &nbsp;}}else{&nbsp; &nbsp; &nbsp; &nbsp;DisplayAlert("Failure", "Photo already exist", "ok");}&nbsp; &nbsp; &nbsp; &nbsp; //clear the notes field&nbsp; &nbsp; &nbsp; &nbsp; notesentry.Text = "";
随时随地看视频慕课网APP
我要回答