PG備忘録

プログラミングいろいろ

データベースの生成・追加・表示のサンプルコード

MainActivity.java

package com.example.orisa.mydb3;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

    //部品の変数
    LinearLayout layout;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //部品の取得
        layout = (LinearLayout)findViewById(R.id.layout);
        tv = (TextView)findViewById(R.id.tv) ;

        //データベースの生成
        MyDbHelper hlp = new MyDbHelper(this);
        SQLiteDatabase db = hlp.getReadableDatabase();

        //データの追加
        ContentValues val = new ContentValues();
        val.put("name", "Ming Ho");
        val.put("age", 44);
        db.insert("person_table", null, val);

        //データの読み出し
        Cursor c = db.query("person_table", new String[]{"name, age"},
                null, null, null, null, null);
        boolean mov = c.moveToFirst();
        while (mov){
            tv.append(String.format("%s: %d才", c.getString(0), c.getInt(1)));
            tv.append("\n");
            mov = c.moveToNext();
        }
        c.close();
        db.close();
    }
}

MyDbHelper

package com.example.orisa.mydb3;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by orisa on 2017/05/30.
 */

public class MyDbHelper extends SQLiteOpenHelper {
    public MyDbHelper(Context context){
        super(context, null, null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE person_table(name TEXT NOT NULL, age TEXT);");

        //データを挿入する
        db.execSQL("INSERT INTO person_table(name, age) values(?,?);", new Object[]{"Adam Smith", 30});
        db.execSQL("INSERT INTO person_table(name, age) values(?,?);", new Object[]{"John Lennon", 40});
        db.execSQL("INSERT INTO person_table(name, age) values(?, ?);", new Object[]{"Paul McCartney", 50});


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}