1.通过点击按钮来执行删除表中数据。(数据库和表的创建不在详细介绍,请自动阅读数据库和表的创建)
第一种方法:直接使用SQL来操作数据库,调用execSQL(sql)语句
public class MainActivity extends AppCompatActivity { private Button mDeleteButton; private MySqliteHelper mMySqliteHelper; private SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMySqliteHelper = DbManger.getIntance(MainActivity.this); mDeleteButton = (Button) findViewById(R.id.delete_btn); //点击按钮删除数据 mDeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { db = mMySqliteHelper.getWritableDatabase(); String sql = "delete from "+Constant.TABLE_NAME+" where "+Constant.ID+" = 2 "; db.execSQL(sql); db.close(); } }); } }
第二种方法:使用android API封装好的删除数据的操作
public class MainActivity extends AppCompatActivity { private Button mDeleteButton; private MySqliteHelper mMySqliteHelper; private SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMySqliteHelper = DbManger.getIntance(MainActivity.this); mDeleteButton = (Button) findViewById(R.id.delete_btn); //点击按钮删除数据 mDeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { db = mMySqliteHelper.getWritableDatabase(); db.delete(Constant.TABLE_NAME,Constant.ID+" = ?",new String[]{"3"}); db.close(); } }); } }
时间: 2024-12-17 04:29:59