簡體   English   中英

如何避免使用Android在sqlite中存儲空值

[英]How to avoid storing null values in sqlite using android

如果我單擊添加按鈕,則值必須存儲在sqLite數據庫中。 我的問題是它存儲的null值又如何避免該值? 幫我啦

//creating database and table

    public class Database extends SQLiteOpenHelper {
            static int dbversion=1;
            static String dbname="expense.db";

            public Database(Context context)
                     {
                super(context, dbname, null, dbversion);
                // TODO Auto-generated constructor stub
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                db.execSQL("create table addsource(source text)");


//inserting values in database

    add.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        Database db=new Database(Sett.this);
                        SQLiteDatabase sb=db.getReadableDatabase(); 

                        sb.execSQL("insert into addsource(source)values('"+sources.getText()+"')");
                        Toast.makeText(getApplicationContext(), "Registered Successfully",Toast.LENGTH_SHORT).show();

                    }
                });

            }

您為什么不測試其價值?

if(sources != null){
    sb.execSQL("insert into addsource(source)values('"+sources.getText()+"')");
}
else{ 
    //insert what you want
}

而且,我認為您不能插入null值,您可以僅使用以下命令插入一個空字符串:

sources.getText()

因此,可以代替sources != null來測試sources.getText().length > 0並插入所需的內容(以防萬一)。

您可以在插入數據庫之前檢查值。將值放入字符串,並在單擊添加按鈕然后插入表中時檢查字符串是否不為空。

您還可以在表創建中使用“非空”

在SQLite Android中創建表

您有3種方法:

1-在創建表中添加NOT NULL:

CREATE TABLE your_table ( column_name INT NOT NULL, ....)

2-選擇使用SELECT時不為空的值:

SELECT column_name FROM your_table WHERE column_name IS NOT NULL

3-檢查變量值以查看其是否為空:

if ( String.ValueOf(source) != null){   // for string example
      // add the source to the database
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM