首页 > 代码库 > 查询表中数据的两种方法(select查)
查询表中数据的两种方法(select查)
1.通过点击按钮来执行查询表中数据。(数据库和表的创建不在详细介绍,请自动阅读数据库和表的创建)
第一种方法:直接使用SQL来操作数据库,调用execSQL(sql)语句
public class MainActivity extends AppCompatActivity { private Button mSelectButton; 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); mSelectButton = (Button) findViewById(R.id.select_btn); //点击按钮查询数据 mSelectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { db = mMySqliteHelper.getWritableDatabase(); String sql = "select * from "+Constant.TABLE_NAME+ " where "+Constant.ID+" = 5"; Cursor cursor = db.rawQuery(sql,null); if(cursor != null){ while(cursor.moveToNext()){ int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.i("MainActivity","person id is "+id); Log.i("MainActivity","person name is "+name); Log.i("MainActivity","person age is "+age); }
第二种方法:使用android API封装好的修改数据的操作
public class MainActivity extends AppCompatActivity { private Button mSelectButton; 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); mSelectButton = (Button) findViewById(R.id.select_btn); //点击按钮查询数据 mSelectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { db = mMySqliteHelper.getWritableDatabase(); Cursor cursor = db.query(Constant.TABLE_NAME,null,"id = ?",new String[]{"5"}, null,null,null); if(cursor != null){ while(cursor.moveToNext()){ int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.i("MainActivity","person id is "+id); Log.i("MainActivity","person name is "+name); Log.i("MainActivity","person age is "+age); } } cursor.close(); db.close(); } }); } }
查询表中数据的两种方法(select查)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。