查询表中数据的两种方法(select查)
Posted 懂你在爱我
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了查询表中数据的两种方法(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查)的主要内容,如果未能解决你的问题,请参考以下文章