首页 > 移动平台 > 详细

Android学习(十) SQLite操作

时间:2015-03-27 19:46:45      阅读:248      评论:0      收藏:0      [点我收藏+]

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);
                }
            }
        });

    }
}

 

Android学习(十) SQLite操作

原文:http://www.cnblogs.com/zhengcheng/p/4372552.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!