SQLite创建表无法正常工作而没有任何错误

时间:2018-03-29 15:08:41

标签: java android database sqlite

我尝试创建一个数据库并在其中创建一个表。正在创建数据库但不是table.it没有显示任何错误,也无法将值插入其中。我想创建一个表并插入从用户收到的数据,但数据不是能够添加到数据库,它既不会显示任何错误。代码如下:

public DataBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

            String q = "CREATE TABLE IF NOT EXISTS " + TABLE_NAMETRY + "(" +
                    COL_ID + " INTEGER PRIMARY KEY, " + COL_NAME + " TEXT, " + COL_PHONE + " TEXT " + ")";`enter code here`
            db.execSQL(q);
    }
    @Override

    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP table if exist "+TABLE_NAMETRY);
        onCreate(db);
    }

    public boolean insertData(String name,String no)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentvalue = new ContentValues();
        contentvalue.put(COL_NAME,name);
        contentvalue.put(COL_PHONE,no);
       long result = db.insert(TABLE_NAMETRY,null,contentvalue);
        if(result==-1)
        return false;
        else
            return true;
    }

public class MainActivity extends AppCompatActivity {
    DataBaseHelper mydb;
    EditText name,no;
    Button b1;
    TextView t1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mydb=new DataBaseHelper(this);

        name=(EditText)findViewById(R.id.name);
        no=(EditText)findViewById(R.id.no);
        t1=(TextView)findViewById(R.id.t1);
        b1=(Button)findViewById(R.id.b1);

        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "Adding Data", Toast.LENGTH_SHORT).show();
                AddData();
            }
        });
    }
    public void AddData()
    {
        boolean check= mydb.insertData(name.getText().toString(),no.getText().toString());
        if(check==true)
            t1.setText("data submitted");
        else
            t1.setText("data not submitted");

    }
}

1 个答案:

答案 0 :(得分:-1)

帮助器很可能是创建表(onCreate)然后删除它(onUpgrade)。

这里我如何创建我的帮助器,注意databaseVersion,因为在执行(onUpgrade)时这很重要

public class DatabaseOpenHelper extends SQLiteOpenHelper {
private final static String databaseName = "Your_DB_Name";
private final static int databaseVersion = 13;

DatabaseOpenHelper(Context context) {
    super(context, databaseName, null, databaseVersion);
}

@Override
public void onCreate(SQLiteDatabase db) { // Do Create Your Table Here }

@Override
public void onUpgrade(SQLiteDatabase db, int Old_Version, int New_Version) { //Delete Your tables here if they exists}