main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="读取数据库总的值" /> </LinearLayout>
main.java
package com.hdjc.sqllitedemo; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { Button btnQuery; SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 每个应用程序都有独立的Android数据库。不会互相影响。 // 创建一个数据库文件。 db = openOrCreateDatabase("first.db", MODE_PRIVATE, null); // 创建一张表 db.execSQL("create table if not exists tb_user(id integer primary key autoincrement,name text not null,age integer not null,sex text not null)"); // 插入数据 /* * db.execSQL("insert into tb_user(name,sex,age) values(‘李四‘,‘男‘,20)"); * db.execSQL("insert into tb_user(name,sex,age) values(‘王五‘,‘女‘,28)"); * db.execSQL("insert into tb_user(name,sex,age) values(‘赵六‘,‘女‘,30)"); */ btnQuery = (Button) findViewById(R.id.button1); btnQuery.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Cursor c = db.rawQuery("select * from tb_user", null); while (c.moveToNext()) { int id = c.getInt(0); String name = c.getString(c.getColumnIndex("name")); String sex = c.getString(c.getColumnIndex("sex")); int age = c.getInt(c.getColumnIndex("age")); Log.i("user", "id:" + id + ",name:" + name + ",sex:" + sex + ",age:" + age); } } }); } }
原文:http://www.cnblogs.com/zhengcheng/p/4372552.html