1.通过点击按钮来执行修改表中数据。(数据库和表的创建不在详细介绍,请自动阅读数据库和表的创建)
第一种方法:直接使用SQL来操作数据库,调用execSQL(sql)语句
public class MainActivity extends AppCompatActivity { private Button mPudateButton; 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); mPudateButton = (Button) findViewById(R.id.update_btn); //点击按钮插入数据 mPudateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { db = mMySqliteHelper.getWritableDatabase(); String sql = "update "+Constant.TABLE_NAME+ " set "+Constant.NAME+ " = ‘小明‘ where "+Constant.ID+" = ‘3‘"; db.execSQL(sql); db.close(); } }); } }
第二种方法:使用android API封装好的修改数据的操作
public class MainActivity extends AppCompatActivity { private Button mUpdateButton; 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); mUpdateButton = (Button) findViewById(R.id.update_btn); //点击按钮插入数据 mUpdateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { db = mMySqliteHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(Constant.NAME,"小七"); db.update(Constant.TABLE_NAME,values,""+Constant.ID+" = ?",new String[]{"1"}); db.close(); } }); } }
时间: 2024-09-30 04:41:26