1.通过点击按钮来执行往表中添加数据。(数据库和表的创建不在详细介绍,请自动阅读数据库和表的创建)
第一种方法:直接使用SQL来操作数据库,调用execSQL(sql)语句
public class MainActivity extends AppCompatActivity { private Button mInsertButton; 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); mInsertButton = (Button) findViewById(R.id.insert_btn); //点击按钮插入数据 mInsertButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { db = mMySqliteHelper.getWritableDatabase(); String sql = "insert into "+Constant.TABLE_NAME+"("+ Constant.NAME+","+Constant.AGE+")values(‘张三‘,16)"; db.execSQL(sql); String sql2 = "insert into "+Constant.TABLE_NAME+"("+ Constant.NAME+","+Constant.AGE+")values(‘李四‘,20)"; db.execSQL(sql2); db.close(); } }); } }
第二种方法:使用android API封装好的增加数据的操作
public class MainActivity extends AppCompatActivity { private Button mInsertButton; 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); mInsertButton = (Button) findViewById(R.id.insert_btn); //点击按钮插入数据 mInsertButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { db = mMySqliteHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(Constant.NAME,"王五"); values.put(Constant.AGE,21); db.insert(Constant.TABLE_NAME,null,values); db.close(); } }); } }
时间: 2024-11-06 15:19:05